From a77ba24ca0b2a8aaee86c034f3da32d6ef0129af Mon Sep 17 00:00:00 2001 From: Rich Megginson Date: May 22 2006 18:14:46 +0000 Subject: Initial import of admin server console into its own module --- diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3f06113 --- /dev/null +++ b/LICENSE @@ -0,0 +1,222 @@ + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/build.properties b/build.properties new file mode 100755 index 0000000..5f7cdcc --- /dev/null +++ b/build.properties @@ -0,0 +1,28 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# END COPYRIGHT BLOCK +# +# Properties to control the build + +lang=en + +admservconsole.root=.. +admservconsole.version=1.0.2 +admservconsole.gen.version=1.0 +brand=fedora +admservconsole.name=${brand}-as-${admservconsole.version} +admservconsole.gen.name=${brand}-as-${admservconsole.gen.version} diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..01a5a6a --- /dev/null +++ b/build.xml @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/imports.FC2 b/imports.FC2 new file mode 100644 index 0000000..2af41eb --- /dev/null +++ b/imports.FC2 @@ -0,0 +1,23 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# END COPYRIGHT BLOCK +# +# Defines component import locations for FC2 + +# Console SDK +console.import.location=http://directory.fedora.redhat.com/built/components/console/1.0/20051027/RHEL3_x86_gcc3_OPT.OBJ +console.import=console10.tar.gz diff --git a/imports.FC3 b/imports.FC3 new file mode 100644 index 0000000..11189d1 --- /dev/null +++ b/imports.FC3 @@ -0,0 +1,23 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# END COPYRIGHT BLOCK +# +# Defines component import locations for FC3 + +# Console SDK +console.import.location=http://directory.fedora.redhat.com/built/components/console/1.0/20051027/RHEL4_x86_gcc3_OPT.OBJ +console.import=console10.tar.gz diff --git a/imports.HP-UX11i b/imports.HP-UX11i new file mode 100644 index 0000000..40f7ba4 --- /dev/null +++ b/imports.HP-UX11i @@ -0,0 +1,23 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# END COPYRIGHT BLOCK +# +# Defines component import locations for FC2 + +# Console SDK +console.import.location=http://directory.fedora.redhat.com/built/components/console/1.0/20051027/HP-UXB.11.11_OPT.OBJ +console.import=console10.tar.gz diff --git a/imports.Solaris9 b/imports.Solaris9 new file mode 100644 index 0000000..c373849 --- /dev/null +++ b/imports.Solaris9 @@ -0,0 +1,23 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# END COPYRIGHT BLOCK +# +# Defines component import locations for FC2 + +# Console SDK +console.import.location=http://directory.fedora.redhat.com/built/components/console/1.0/20051027/SunOS5.9_OPT.OBJ +console.import=console10.tar.gz diff --git a/src/com/netscape/management/admserv/AdminFrameworkInitializer.java b/src/com/netscape/management/admserv/AdminFrameworkInitializer.java new file mode 100644 index 0000000..89172a3 --- /dev/null +++ b/src/com/netscape/management/admserv/AdminFrameworkInitializer.java @@ -0,0 +1,146 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.client.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.admserv.task.AdminTaskObject; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; + + +/** + * Initializes Admin Server Config framework + */ +public class AdminFrameworkInitializer extends FrameworkInitializer { + private static String PERMID_SECURITY = "SecurityVisibility"; + public static boolean canAccessSecurity = false; + + public AdminFrameworkInitializer(ConsoleInfo consoleInfo) { + Console.setConsoleInfo(consoleInfo); // workaround to classloading static reference problem + UIPermissions uip = new UIPermissions(LDAPUtil.getAdminGlobalParameterEntry()); + canAccessSecurity = uip.hasPermission(PERMID_SECURITY); + TaskPage taskPage = new TaskPage(consoleInfo); + TaskObject root = (TaskObject) taskPage.getModel().getRoot(); + + addPage(taskPage); + String [] taskList = getTaskList(taskPage); + setTaskConsoleInfo(taskPage, consoleInfo); // override cloning of ConsoleInfo + addPage( new AdminResourcePage( + new AdminResourceModel(consoleInfo, taskList))); + RemoteImage imageIcon = new RemoteImage( + AdminServer._resource.getString("admin", "largeIcon")); + setMinimizedImage(imageIcon.getImage()); + + setBannerImage(getBannerImage(consoleInfo)); + setFrameTitle(consoleInfo.getLDAPConnection(), + consoleInfo.getCurrentDN()); + setBannerText(""); + } + + private Image getBannerImage(ConsoleInfo consoleInfo) { + String imageBase="com/netscape/management/admserv/images/"; + return new RemoteImage(imageBase + "admin.gif").getImage(); + } + + private String[] getTaskList(TaskPage taskPage) { + TaskObject root = (TaskObject) taskPage.getModel().getRoot(); + String[] tasks = new String[root.getChildCount()]; + for (int i = 0; i < root.getChildCount(); i++) { + tasks[i] = root.getChildAt(i).getClass().getName(); + } + return tasks; + } + + /** + * TaskPage clones ConsoleInfo when creating a task. We want to + * override that and force all Admin Server tasks to use the same + * adminURL as the AdminServer object. This is important as + * adminURL might change if the port number is changed. + */ + private void setTaskConsoleInfo(TaskPage taskPage, + ConsoleInfo consoleInfo) { + TaskObject root = (TaskObject) taskPage.getModel().getRoot(); + for (int i = 0; i < root.getChildCount(); i++) { + AdminTaskObject task = (AdminTaskObject) root.getChildAt(i); + task.setConsoleInfo( new TaskConsoleInfo(task.getConsoleInfo(), + consoleInfo)); + } + } + + /** + * TaskConsoleInfo class overrides getAdminURL to return the + * value from the ConsoleInfo in the ServerNode + */ + private static class TaskConsoleInfo extends ConsoleInfo { + private ConsoleInfo serverNodeConsoleInfo; + public TaskConsoleInfo(ConsoleInfo taskConsoleInfo, + ConsoleInfo serverNodeConsoleInfo) { + for (Enumeration eKey = taskConsoleInfo.keys(); + eKey.hasMoreElements();) { + Object oKey = eKey.nextElement(); + Object oValue = taskConsoleInfo.get(oKey); + put(oKey, oValue); + } + this.serverNodeConsoleInfo = serverNodeConsoleInfo; + } + public String getAdminURL() { + return serverNodeConsoleInfo.getAdminURL(); + } + }; + + private void removeTask(TaskObject root, String taskName) { + for (int i = 0; i < root.getChildCount(); i++) { + // can not use instanceof because of compilation dependency + if (root.getChildAt(i).getClass().getName().endsWith( + taskName)) { + ((TaskObject) root).remove(i); + break; + } + } + } +} + + +class AdminResourcePage extends ResourcePage { + public AdminResourcePage(IResourceModel model) { + super(model); + } + + public void initialize(Framework framework) { + MenuItemText item = new MenuItemText( + AdminServer._resource.getString("menu", + "HelpAdminServer"), "TODO:description"); + item.addActionListener(new HelpAction()); + framework.addMenuItem(Framework.MENU_HELPWEBHELP, item); + } + + class HelpAction implements ActionListener { + public void actionPerformed(ActionEvent e) { + Help helpSession = new Help(AdminServer._resource); + helpSession.contextHelp("menubar", "adminserverHelpToken"); + } + } +} diff --git a/src/com/netscape/management/admserv/AdminResourceModel.java b/src/com/netscape/management/admserv/AdminResourceModel.java new file mode 100644 index 0000000..8744c43 --- /dev/null +++ b/src/com/netscape/management/admserv/AdminResourceModel.java @@ -0,0 +1,157 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.logging.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.admserv.logging.*; +import netscape.ldap.*; + +import com.netscape.management.client.security.CertificateDialog; +import com.netscape.management.client.security.PKCSConfigDialog; +import com.netscape.management.client.security.CertMigrateWizard; + +public class AdminResourceModel extends ResourceModel implements IMenuInfo { + static String iconSource = "com/netscape/management/client/images/"; + static ResourceSet _resource = new ResourceSet("com.netscape.management.admserv.admserv"); + IResourceObject[]_selection; + + static public String MENU_CERT_DIALOG = "CERTIFICATE SETUP WIZARD"; + static public String MENU_PKCS11_CONFIG = "CERTIFICATE MANAGEMENT"; + static public String MENU_IMPORT_CERT = "IMPORT CERTIFICATE"; + + ConsoleInfo _consoleInfo; + + /** + * Returns supported menu categories + */ + public String[] getMenuCategoryIDs() { + return new String[]{ Framework.MENU_FILE//, + //ResourcePage.MENU_CONTEXT + }; + } + + + /** + * constrcutor and initialize all the internal variables + */ + public AdminResourceModel(ConsoleInfo ci, String[] taskList) { + + + _consoleInfo = ci; + + ResourceObject root = new AdminServerNode(ci, taskList); + + root.add(new LoggingNode(ci, taskList)); + + setRoot(root); + } + + + public IMenuItem[] getMenuItems(String categoryID) { + + ResourceSet _resource = new ResourceSet("com.netscape.management.client.default"); + if (AdminFrameworkInitializer.canAccessSecurity && categoryID.equals(Framework.MENU_FILE)) { + MenuItemCategory category = new MenuItemCategory("security", _resource.getString("menu", "FileSecurity")); + category.add(new MenuItemText(MENU_CERT_DIALOG, + _resource.getString("menu", "FileManageCert"), + "TODO:description", + new SecurityAction(MENU_CERT_DIALOG))); + category.add(new MenuItemText(MENU_PKCS11_CONFIG, + _resource.getString("menu", "FilePKCS11Config"), + "TODO:description", + new SecurityAction(MENU_PKCS11_CONFIG))); + category.add(new MenuItemText(MENU_IMPORT_CERT, + _resource.getString("menu", "FileImportCert"), + "TODO:description", + new SecurityAction(MENU_IMPORT_CERT))); + return new IMenuItem[]{ + category, + new MenuItemSeparator() + }; + } + return null; + } + + class SecurityAction implements ActionListener { + String _id; + public SecurityAction(String id) { + _id = id; + } + public void actionPerformed(ActionEvent e) { + if (_id.equals(MENU_CERT_DIALOG)) { + JFrame f = UtilConsoleGlobals.getActivatedFrame(); + try { + if (f != null && f instanceof Framework){ + ((Framework)f).setBusyCursor(true); + } + CertificateDialog certDialog = new CertificateDialog(f, _consoleInfo, (String)_consoleInfo.get("SIE")); + certDialog.setVisible(true); + } + finally { + if (f != null && f instanceof Framework){ + ((Framework)f).setBusyCursor(false); + } + } + } else if (_id.equals(MENU_PKCS11_CONFIG)) { + JFrame f = UtilConsoleGlobals.getActivatedFrame(); + try { + if (f != null && f instanceof Framework){ + ((Framework)f).setBusyCursor(true); + } + PKCSConfigDialog pkcsConfig = new PKCSConfigDialog(f, _consoleInfo, (String)_consoleInfo.get("SIE")); + pkcsConfig.setVisible(true); + } + finally { + if (f != null && f instanceof Framework){ + ((Framework)f).setBusyCursor(false); + } + } + } else if (_id.equals(MENU_IMPORT_CERT)) { + CertMigrateWizard certMigrate = new CertMigrateWizard(null, _consoleInfo, (String)_consoleInfo.get("SIE")); + certMigrate.setVisible(true); + } + } + } + + public void actionObjectSelected(IPage viewInstance, + IResourceObject[] selection, + IResourceObject[] previousSelection) { + super.actionObjectSelected(viewInstance, selection, + previousSelection); + _selection = selection; + } + + /** + * Notification that a menu item has been selected. + */ + public void actionMenuSelected(IPage viewInstance, IMenuItem item) { + } + +} diff --git a/src/com/netscape/management/admserv/AdminServer.java b/src/com/netscape/management/admserv/AdminServer.java new file mode 100644 index 0000000..dede0ce --- /dev/null +++ b/src/com/netscape/management/admserv/AdminServer.java @@ -0,0 +1,442 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import java.net.*; +import java.io.*; +import javax.swing.*; +import com.netscape.management.client.*; +import com.netscape.management.client.console.*; +import com.netscape.management.admserv.panel.IRestartControl; +import com.netscape.management.admserv.config.BaseConfigPanel; +import com.netscape.management.client.topology.*; +import com.netscape.management.client.util.*; +import com.netscape.management.nmclf.*; +import com.netscape.management.admserv.panel.*; +import netscape.ldap.*; + +/** + * Netscape admin server configuration entry point. The directory + * server needs to contain the name of this class in order for the topology + * view to load this class. + */ +public class AdminServer extends AbstractServerObject implements SuiConstants { + public static ResourceSet _resource = new ResourceSet("com.netscape.management.admserv.admserv"); + + ConsoleInfo _consoleInfo; + int _serverStatus; + private int adminUrlNodeDataIndex = -1; + + /** + * Implements the IServerObject interface. Initializes the page with + * the global information. + * + * @param info - global information. + */ + public void initialize(ConsoleInfo info) { + super.initialize(info); + _consoleInfo = info; + setIcon(new RemoteImage(_resource.getString("admin", "smallIcon"))); + _canRestartFromConsole = !info.getAdminURL().startsWith("https"); + } + + /** + * Restart activator is used as a repository for various restart control parameters. + * The reference to the activator is stored in the ConsoleInfo. panel/RestartOperation.java + * is reading the restart parameters which are set by config panels and operations. + */ + protected boolean _needsAutoRestart = false; + protected boolean _canRestartFromConsole; // set in initialize() + protected String _postRestartURL = null; + protected boolean _isShutdown = false; + + private IRestartControl _restartControl = new IRestartControl() { + public void setNeedsAutoRestart(boolean flag) { + _needsAutoRestart = flag; + } + public boolean needsAutoRestart() { + return _needsAutoRestart; + } + + public void setCanRestartFromConsole(boolean flag) { + _canRestartFromConsole = flag; + } + public boolean canRestartFromConsole() { + return _canRestartFromConsole; + } + + public void setPostRestartURL(String url) { + _postRestartURL = url; + } + + public String getPostRestartURL() { + return _postRestartURL; + } + + public void setServerShutdown(boolean flag) { + _isShutdown = flag; + } + public boolean isServerShutdown() { + return _isShutdown; + } + + + }; + + /* TODO move to AdminTaskPage/ResourcePage/FrameworkInitializer + IFrameworkListener _closeListener = new IFrameworkListener() { + public void pageSelectionChanged(FrameworkEvent e) {} + + public void actionViewClosing(FrameworkEvent e) throws CloseVetoException { + Debug.println("window closing, needs restart =" + _needsAutoRestart); + if (_restartControl.needsAutoRestart()) { + SuiOptionPane.showMessageDialog(_frame, + _resource.getString("restart","mustRestart"), + _resource.getString("restart","title"), + SuiOptionPane.INFORMATION_MESSAGE); + + AdminOperation operation = new RestartOperation(_consoleInfo); + operation.monitorOperation(""); + String title = _resource.getString("taskName","restart"); + DialogFrame dialog = new DialogFrame(_frame, title, operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + } + } + }; + */ + + private boolean run(IPage viewInstance) { + // do not run if the server is down + if (getServerStatus() == IServerObject.STATUS_STOPPED) { + Frame frame = viewInstance.getFramework().getJFrame(); + String title = _resource.getString("error","OpenServerTitle"); + String msg = java.text.MessageFormat.format( + _resource.getString("error","CanNotOpenServer"), + new Object[]{ getName()}); + BaseConfigPanel.clearProgressIndicator( + (Component) viewInstance); + SuiOptionPane.showMessageDialog(frame, msg, title, + SuiOptionPane.ERROR_MESSAGE); + return false; + } + + // Augment the console info with the server name + _consoleInfo.put("SIE", getSIE()); + _consoleInfo.put("SIE_VERSION", getProductVersion()); + _consoleInfo.put("SERVER_NAME", getName()); + _consoleInfo.put("HOST_NAME", getHostName()); + _consoleInfo.put(IRestartControl.ID, _restartControl); + + createFramework(); + + return true; + } + + /** + * This function is called when the admin server is double clicked on the topology view. + */ + public boolean run(IPage viewInstance, + IResourceObject selectionList[]) { + // create new frame + if (selectionList.length == 1) { + return run(viewInstance); + } + + // Do not run if the server is down + if (getServerStatus() == IServerObject.STATUS_STOPPED) { + Frame frame = viewInstance.getFramework().getJFrame(); + String title = _resource.getString("error","OpenServerTitle"); + String msg = java.text.MessageFormat.format( + _resource.getString("error","CanNotOpenServer"), + new Object[]{ getName()}); + BaseConfigPanel.clearProgressIndicator( + (Component) viewInstance); + SuiOptionPane.showMessageDialog(frame, msg, title, + SuiOptionPane.ERROR_MESSAGE); + return false; + } + + for (int i = 0; i < selectionList.length; i++) { + if (!(selectionList[i] instanceof ServerNode)) { + Debug.println("can't run, selection is " + + selectionList[i].getClass().getName()); + return false; + } + ServerNode node = (ServerNode) selectionList[i]; + if (!(node.getServerObject() instanceof AdminServer)) { + Debug.println("can't run, server is " + + node.getServerObject().getClass().getName()); + return false; + } + + } + + createFramework(); + + return true; + } + + + protected void createFramework() { + Framework frame = new Framework( + new AdminFrameworkInitializer(_consoleInfo)); + StatusItemSecureMode _statusSecureMode = + new StatusItemSecureMode(Framework.STATUS_SECURE_MODE); + _statusSecureMode.setSecureMode( + _consoleInfo.getAdminURL().startsWith("https")); + frame.addStatusItem(_statusSecureMode, IStatusItem.LEFTFIRST); + _statusSecureMode.setToolTipText(_consoleInfo.getAdminURL()); + } + + + // return the host in which this server is installed + protected String getHostName() { + return (String)_nodeDataTable.get("serverHostName"); + } + + // return SIE name "admin-serv-" + protected String getSIE() { + return (String)_nodeDataTable.get("cn"); + } + + // return the Server version number e.g. "4.1" + protected String getProductVersion() { + return (String)_nodeDataTable.get("nsProductVersion"); + } + + public ConsoleInfo getConsoleInfo() { + return _consoleInfo; + } + + + private URL _serverURL = null; + private URLConnection _serverConnection = null; + + /** + * Implements the IServerObject interface. + */ + public synchronized int getServerStatus() { + // for admin server, just check whether connections are accepted on the URL; + // if the URL does not respond, then it is down. Otherwise it is up. + + // In case the method is called before AdminServer in initialized + if (_consoleInfo == null) { + return STATUS_UNKNOWN; + } + + + try { + String adminURL = _consoleInfo.getAdminURL() + "admin-serv/tasks/operation/StatusPing"; + AdmTask task = new AdmTask(new URL(adminURL), + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + task.exec(); + int status = task.getStatus(); + if (status == 0) { + _serverStatus = STATUS_STARTED; + } else if (task.getException() != null && task.getException() + instanceof java.net.SocketException) { + _serverStatus = STATUS_STOPPED; + } else { + _serverStatus = STATUS_UNKNOWN; + } + return _serverStatus; + } catch (MalformedURLException ex) { + Debug.println("ERROR AdminConfigData.isRunning: bad URL " + + _consoleInfo.getAdminURL()); + return _serverStatus = STATUS_UNKNOWN; + } + + + } + + /** + * Implements the IServerObject interface. This will launch the + * necessary CGI to clone the configuration of the reference server + * to this server. Only the following attributes are cloned: + * + * + * @param referenceDN - DN of server to clone from. + */ + public void cloneFrom(String referenceDN) { + String configDN = "cn=configuration," + referenceDN; + String configURL = null; + try { + // First, get the configuration information to clone using the referenceDN. + LDAPConnection ldc = _consoleInfo.getLDAPConnection(); + if (ldc == null) { + ldc = new LDAPConnection(); + } + if (ldc.isConnected() == false) { + ldc.connect(_consoleInfo.getHost(), _consoleInfo.getPort(), + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + } + LDAPEntry entry = ldc.read(configDN); + String addresses = LDAPUtil.flatting( + entry.getAttribute("nsadminaccessaddresses", + LDAPUtil.getLDAPAttributeLocale())); + String hosts = LDAPUtil.flatting( + entry.getAttribute("nsadminaccesshosts", + LDAPUtil.getLDAPAttributeLocale())); + String cache = LDAPUtil.flatting( + entry.getAttribute("nsadmincachelifetime", + LDAPUtil.getLDAPAttributeLocale())); + String dsgw = LDAPUtil.flatting( + entry.getAttribute("nsadminenabledsgw", + LDAPUtil.getLDAPAttributeLocale())); + String endUser = LDAPUtil.flatting( + entry.getAttribute("nsadminenableenduser", + LDAPUtil.getLDAPAttributeLocale())); + String oneAclDir = LDAPUtil.flatting( + entry.getAttribute("nsadminoneacldir", + LDAPUtil.getLDAPAttributeLocale())); + String defaultAccLang = LDAPUtil.flatting( + entry.getAttribute("nsdefaultacceptlanguage", + LDAPUtil.getLDAPAttributeLocale())); + boolean enableDSGW; + boolean enableEndUser; + if (dsgw != null && dsgw.equalsIgnoreCase("off")) { + enableDSGW = false; + } else { + enableDSGW = true; + } + if (endUser != null && endUser.equalsIgnoreCase("off")) { + enableEndUser = false; + } else { + enableEndUser = true; + } + + // Invoke CGI to configure the server with the cloned configuration information. + // Some attributes, such as nsadminenableenduser, must be forced set. + configURL = + new String(_consoleInfo.getAdminURL() + "admin-serv/tasks/Configuration/ServerSetup?op=force_set" + + "&configuration.nsadminaccessaddresses=" + + addresses + "&configuration.nsadminaccesshosts=" + + hosts + "&configuration.nsadmincachelifetime=" + + cache + "&configuration.nsadminoneacldir=" + oneAclDir + + "&configuration.nsdefaultacceptlanguage=" + + defaultAccLang); + if (enableDSGW == true) { + configURL = configURL + "&configuration.nsadminenabledsgw="; + } else { + configURL = configURL + "&configuration.nsadminenabledsgw=off"; + } + if (enableEndUser == true) { + configURL = configURL + "&configuration.nsadminenableenduser="; + } else { + configURL = configURL + "&configuration.nsadminenableenduser=off"; + } + Debug.println("TRACE AdminServer.cloneFrom: configURL = " + + configURL); + + // Need to make this another thread. Display a dialog to show progress! + URL configAdminURL = new URL(configURL); + // Is authenticating with the ConsoleInfo correct??? + AdmTask task = new AdmTask(configAdminURL, + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + int execStatus = task.exec(); + int taskStatus = task.getStatus(); + String title = _resource.getString("status","cloneTitle"); + if (execStatus == 0 && taskStatus == 0) { + Debug.println("TRACE AdminServer.cloneFrom: config CGI succeeded!"); + String msg = java.text.MessageFormat.format( + _resource.getString("status", + "cloneSucceeded"), new Object[]{ getName()}); + SuiOptionPane.showMessageDialog(null, msg, title, + SuiOptionPane.INFORMATION_MESSAGE); + } else { + // Either the exec or the task failed. + Debug.println( + "ERROR AdminServer.cloneFrom: config CGI status = " + + (execStatus == 0 ? taskStatus : execStatus)); + String msg = java.text.MessageFormat.format( + _resource.getString("status", "cloneFailed"), + new Object[]{ getName()}); + SuiOptionPane.showMessageDialog(null, msg, title, + SuiOptionPane.ERROR_MESSAGE); + } + } + catch (LDAPException e) { + // TODO: Use SuiOptionPane error message + Debug.println( + "ERROR AdminServer.cloneFrom: LDAP read failed: " + + configDN); + } + catch (MalformedURLException e) { + // TODO: Use SuiOptionPane error message + Debug.println("ERROR AdminServer.cloneFrom: Bad URL: " + + configURL); + } + } + + /** + * Number of entries for this node. + * Implements INodeInfo + * + * @return number of entries + */ + public int getNodeDataCount() + { + adminUrlNodeDataIndex = super.getNodeDataCount(); + return adminUrlNodeDataIndex + 1; + } + + public boolean isCloningEnabled() + { + return false; + } + + /** + * Return node entry at specified index. + * Implements INodeInfo + * + * @return the specified node data + */ + public NodeData getNodeData(int index) { + if(index == adminUrlNodeDataIndex) + { + String port = null; // legal value, if null, this NodeData will not appear in panel + String url = _consoleInfo.getAdminURL(); + int portIndex = url.lastIndexOf(':'); + if(portIndex != -1) + port = url.substring(portIndex+1).replace('/', ' ').trim(); + return new NodeData("", _resource.getString("infopanel", "Port"), port, false); + } + else + { + return super.getNodeData(index); + } + } +} diff --git a/src/com/netscape/management/admserv/AdminServerNode.java b/src/com/netscape/management/admserv/AdminServerNode.java new file mode 100644 index 0000000..dd2de66 --- /dev/null +++ b/src/com/netscape/management/admserv/AdminServerNode.java @@ -0,0 +1,201 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.tree.*; +import com.netscape.management.nmclf.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; +import com.netscape.management.admserv.config.*; +import netscape.ldap.*; + + +public class AdminServerNode extends ResourceObject implements IMenuInfo { + public static ResourceSet _resource; + public static Icon _icon; + public static String _i18nMenuConfig, _i18nMenuRestart, _i18nMenuStop; + public static String _i18nDescrMenuConfig, _i18nDescrMenuRestart, + _i18nDescrMenuStop; + public static String _i18nStopTask, _i18nAckStop; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.admserv"); + _icon = new RemoteImage(_resource.getString("admin", "smallIcon")); + _i18nMenuConfig = _resource.getString("menu", "Config"); + _i18nMenuRestart = _resource.getString("menu", "Restart"); + _i18nMenuStop = _resource.getString("menu", "Stop"); + _i18nDescrMenuConfig = _resource.getString("menuDescription", "ConfigAdmin"); + _i18nDescrMenuRestart = + _resource.getString("menuDescription", "RestartAdmin"); + _i18nDescrMenuStop = _resource.getString("menuDescription", "StopAdmin"); + _i18nAckStop = _resource.getString("stop", "ack"); + _i18nStopTask = _resource.getString("taskName", "stop"); + + } + + static public String MENU_CONFIG = "CONFIG"; + static public String MENU_RESTART = "RESTART"; + static public String MENU_STOP = "STOP"; + + private BaseConfigPanel _configPanel; + private boolean _menuConfigEnabled, _menuRestartEnabled, + _menuStopEnabled; + + private ConsoleInfo _consoleInfo; + + public AdminServerNode(ConsoleInfo ci, String[] taskList) { + super(AdminServer._resource.getString("admin","title")); + + _consoleInfo = ci; + + //If a task is not visible to the user, then it should not be accessable + //from the resorce tree + _menuConfigEnabled = findTask("task.ServerSetup", taskList); + _menuRestartEnabled = findTask("task.Restart", taskList); + _menuStopEnabled = findTask("task.Stop", taskList); + + setAllowsChildren(true); + } + + private boolean findTask(String task, String[] list) { + for (int i = 0; i < list.length; i++) { + if (list[i].endsWith(task)) + return true; + } + return false; + } + + public Icon getIcon() { + return _icon; + } + + public String[] getMenuCategoryIDs() { + return new String[]{ ResourcePage.MENU_OBJECT, + ResourcePage.MENU_CONTEXT }; + } + + public IMenuItem[] getMenuItems(String categoryID) { + if ((categoryID.equals(ResourcePage.MENU_OBJECT)) || + (categoryID.equals(ResourcePage.MENU_CONTEXT))) { + return new IMenuItem[]{ new MenuItemSeparator(), + new MenuItemText(MENU_CONFIG, _i18nMenuConfig, + _i18nDescrMenuConfig, _menuConfigEnabled), + new MenuItemText(MENU_RESTART, _i18nMenuRestart, + _i18nDescrMenuRestart, _menuRestartEnabled), + new MenuItemText(MENU_STOP, _i18nMenuStop, + _i18nDescrMenuStop, _menuStopEnabled)}; + } + return null; + } + + public void actionMenuSelected(IPage viewInstance, IMenuItem item) { + if (viewInstance instanceof ResourcePage) { + if (item.getID().equals(MENU_CONFIG)) { + ResourcePage page = (ResourcePage) viewInstance; + _configPanel = null; + page.setCustomPanel(getCustomPanel()); + } else if (item.getID().equals(MENU_STOP)) { + ResourcePage page = (ResourcePage) viewInstance; + + int userSelection = SuiOptionPane.showConfirmDialog(page, + _i18nAckStop, _i18nStopTask, + SuiOptionPane.YES_NO_OPTION); + + if (userSelection != SuiOptionPane.YES_OPTION) { + return; + } + + AdminOperation operation = new StopOperation(_consoleInfo); + operation.monitorOperation(""); + String title = + AdminServer._resource.getString("taskName","stop"); + DialogFrame dialog = new DialogFrame(page, title, + operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + } else if (item.getID().equals(MENU_RESTART)) { + ResourcePage page = (ResourcePage) viewInstance; + + if (!canRestartFromConsole(page)) + return; + + AdminOperation operation = + new RestartOperation(_consoleInfo); + operation.monitorOperation(""); + String title = + AdminServer._resource.getString("taskName","restart"); + DialogFrame dialog = new DialogFrame(page, title, + operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + } else { + Debug.println("Not Yet Implemented: " + item); + } + } + } + + private boolean canRestartFromConsole(JPanel parent) { + + IRestartControl restartControl = + (IRestartControl)_consoleInfo.get(IRestartControl.ID); + if (restartControl != null) { + if (!restartControl.canRestartFromConsole()) { + String msg = + AdminServer._resource.getString("restart","canNotRestart"); + SuiOptionPane.showMessageDialog(parent, msg, getName(), + SuiOptionPane.ERROR_MESSAGE); + return false; + } + } else { + Debug.println("RestartOperation: restart activator not in ConsoleInfo"); + } + return true; + } + + + public Component getCustomPanel() { + if (!_menuConfigEnabled) + return null; + + if (_configPanel == null || !_configPanel.isInitialized()) { + _configPanel = new BaseConfigPanel( + new AdminConfigPanel(_consoleInfo)); + } + return _configPanel; + } + + /** + * Called when this object needs to execute, (when user double-clicks or menu Open) + * @return success or failure of run operation + * Called by: ResourceModel + */ + public boolean run(IPage viewInstance, IResourceObject selection[]) { + return false; + } +} diff --git a/src/com/netscape/management/admserv/AdminServerProduct.java b/src/com/netscape/management/admserv/AdminServerProduct.java new file mode 100644 index 0000000..57f22a3 --- /dev/null +++ b/src/com/netscape/management/admserv/AdminServerProduct.java @@ -0,0 +1,373 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Vector; +import java.util.StringTokenizer; +import netscape.ldap.LDAPConnection; +import netscape.ldap.LDAPEntry; +import netscape.ldap.LDAPAttribute; +import netscape.ldap.LDAPException; +import com.netscape.management.nmclf.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.client.topology.IProductObject; +//import com.netscape.management.client.topology.KeyCertMigrationDialog; +import com.netscape.management.client.util.Debug; +import com.netscape.management.client.util.AdmTask; +import com.netscape.management.client.util.LDAPUtil; +import com.netscape.management.client.util.URLByteEncoder; +import com.netscape.management.client.util.ResourceSet; +import com.netscape.management.client.util.UtilConsoleGlobals; + + + + +/** + * Netscape admin server migration entry point. The directory server + * needs to contain the name of this class in order for the topology + * view to load this class for migrating the admin server. + * + * @author phlee + * @date 01/09/98 + */ + +public class AdminServerProduct implements IProductObject { + + protected ConsoleInfo _consoleInfo; // global information + //protected KeyCertMigrationDialog _keyCert; + + + /** + * constructor. + */ + public AdminServerProduct() { + } + + + /*public static void main(String args[]) { + AdminServerProduct asp = new AdminServerProduct(); + ConsoleInfo consoleInfo = null; + try { + LDAPConnection connection = new LDAPConnection(); + connection.connect("awing", 3000, "uid=admin, ou=Administrators, ou=TopologyManagement, o=NetscapeRoot", "admin"); + consoleInfo = new ConsoleInfo("buddha.mcom.com", 8081, "admin", "admin", "ou=mcom.com, o=NetscapeRoot"); + consoleInfo.setAdminURL("http://buddha.mcom.com:8081/"); + consoleInfo.setBaseDN("cn=admin-serv-buddha, ou=mcom.com, o=NetscapeRoot"); + consoleInfo.setCurrentDN("cn=admin-serv-buddha, ou=mcom.com, o=NetscapeRoot"); + consoleInfo.setLDAPConnection(connection); + } catch (Exception e) {System.out.println(e); e.printStackTrace();} + asp.initialize(consoleInfo); + asp.migrate("c:\\netscape", "c:\\tmp", "cn=Server Group, cn=buddha.mcom.com, ou=mcom.com, o=NetscapeRoot", false); + }*/ + + /** + * Implements the IProductObject interface. Initializes the page with + * the global information. + * + * @param info - global information. + */ + public void initialize(ConsoleInfo info) { + _consoleInfo = info; + } + + + /** + * Implements the IProductObject interface. Starts the Admin Server + * migration process. Since there can only be one admin server per + * admin group, migration always results in the overwriting of the + * existing SIE. Also, since the admin server that is being invoked + * to do the migration via URL belongs to the target config root, + * the targetDN is also unused. Moreover, the server parameter is not + * needed since there can only be one admin server per server root. + * + * @param serverRoot - directory path for the migration origin. + * @param server - the server to migrate from the serverRoot. + * @param targetDN - the destination admin group DN. + * @param overwrite - whether to overwrite existing SIE. + * @return boolean value indicating whether the process succeeded (true) + * or failed (false). + */ + public boolean migrate(String serverRoot, String server, + String targetDN, boolean overwrite) { + + //ResourceSet resource = new ResourceSet("com.netscape.management.admserv.admserv"); + ResourceSet resource = AdminServer._resource; + String adminURL = _consoleInfo.getAdminURL(); + if (adminURL == null || adminURL.equals("")) { + Debug.println("ERROR AdminServerProduct.migrate: admin URL is not available."); + return false; + } + + if (migrateConfig(adminURL, serverRoot) == false) { + Debug.println("ERROR AdminServerProduct.migrate: migrateConfig failed."); + String msg = resource.getString("status", "migrateConfigFailed"); + String title = resource.getString("status", "migrateTitle"); + SuiOptionPane.showMessageDialog(null, msg, title, + SuiOptionPane.ERROR_MESSAGE); + return false; + } + + /*String commandString = new String(adminURL + "admin-serv/tasks/configuration/ListAlias"); + Hashtable args = new Hashtable(); + args.put("serverRoot", serverRoot); + args.put("serverVer" , "3"); + + Vector aliasList = new Vector(); + try { + URL command = new URL(commandString); + AdmTask task = new AdmTask(command, + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + task.setArguments(args); + int execStatus = task.exec(); + if (execStatus != 0) { + Debug.println("ERROR AdminServerProduct.migrateKeyCert: exec failed"); + return false; + } else { + String list = (String)(task.getResult("aliasList")); + StringTokenizer st = new StringTokenizer(list, ",", false); + while (st.hasMoreTokens()) { + aliasList.addElement(st.nextToken()); + } + } + } catch (Exception e) { + Debug.println("AdminServerProduct:"+e); + } + + _keyCert = new KeyCertMigrationDialog( + UtilConsoleGlobals.getActivatedFrame(), _consoleInfo, + serverRoot, aliasList, server, + getTargetAdminServerID(targetDN), ""); + if (_keyCert == null) { + Debug.println("ERROR AdminServerProduct.migrate: could not create KeyCertMigrationDialog."); + return false; + }*/ + /*String newAlias = getTargetAdminServerID(targetDN); + if (newAlias == null) { + return false; + } + Absolute path of file containing the absolute path to key/cert + String adminConfigFile = serverRoot + "/admin-serv/config/ns-admin.conf"; + _keyCert.setConfigFile(adminConfigFile); + _keyCert.setNewAlias(newAlias); + _keyCert.setPassword("");*/ + /*_keyCert.show(); + if (_keyCert.isCancel()) { + Debug.println("TRACE AdminServerProduct.migrate: skipping migrateKeyCert"); + }*/ + /*else { + if (migrateKeyCert(serverRoot) == false) { + Debug.println("ERROR AdminServerProduct.migrate: migrateKeyCert failed"); + String msg = resource.getString("status", "migrateKeyCertFailed"); + String title = resource.getString("status", "migrateTitle"); + SuiOptionPane.showMessageDialog(null, msg, title, SuiOptionPane.ERROR_MESSAGE); + return false; + } + }*/ + + String msg = resource.getString("status", "migrateSucceeded"); + String title = resource.getString("status", "migrateTitle"); + SuiOptionPane.showMessageDialog(null, msg, title, + SuiOptionPane.INFORMATION_MESSAGE); + + return true; // Success! + } + + + /** + * Implements the IProductObject interface. Starts the Admin Server + * creation process. + * + * @param targetDN - the admin group DN where the new instance is to be + * created. + * @return boolean value indicating whether the process succeeded (true) + * or failed (false). + */ + public boolean createNewInstance(String targetDN) { + Debug.println("trace AdminServerProduct.createNewInstance: not implemented."); + return false; + } + + + protected boolean migrateConfig(String adminURL, String serverRoot) { + + String commandString = + new String(adminURL + "admin-serv/tasks/operation/MigrateConfig" + + "?oldServerRoot=" + URLByteEncoder.encodeUTF8(serverRoot)); + Debug.println( + "TRACE AdminServerProduct.migrateConfig: MigrateConfig commandString = " + + commandString); + + try { + URL command = new URL(commandString); + AdmTask task = new AdmTask(command, + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + int execStatus = task.exec(); + if (execStatus != 0) { + System.out.println("ERROR AdminServerProduct.migrateConfig: exec failed"); + return false; + } + int status = task.getStatus(); + if (status != 0) { + System.out.println( + "ERROR AdminServerProduct.migrateConfig: exec status: " + + status + ": " + task.getResult("NMC_ErrInfo")); + return false; + } + } catch (MalformedURLException e) { + Debug.println( + "TRACE AdminServerProduct.migrateConfig: Bad URL: " + e); + return false; + } + catch (Exception e) { + Debug.println( + "TRACE AdminServerProduct.migrateConfig: unhandled exception: " + e); + return false; + } + + return true; + } + + + protected String getTargetAdminServerID(String targetDN) { + LDAPConnection ldc = _consoleInfo.getLDAPConnection(); + if (ldc == null) { + Debug.println("ERROR AdminServerProduct.getTargetAdminServerID: no LDAPConnection"); + return null; + } + String productDN = null; + String serverDN = null; + String serverName = null; + try { + LDAPEntry entry = ldc.read(targetDN); + if (entry == null) { + Debug.println( + "ERROR AdminServerProduct.getTargetAdminServerID: could not get entry = " + + targetDN); + return null; + } + // Need to find the Fedora Administration Server product. + LDAPAttribute attribute = entry.getAttribute("uniquemember", + LDAPUtil.getLDAPAttributeLocale()); + if (attribute == null) { + Debug.println("ERROR AdminServerProduct.getTargetAdminServerID: no 'uniquemember' attribute"); + return null; + } + Enumeration e = attribute.getStringValues(); + while (e.hasMoreElements()) { + productDN = (String) e.nextElement(); + if (productDN.startsWith("cn=Fedora Administration Server")) { + break; + } + productDN = null; + } + + // Get the single admin server instance. + if (productDN == null) { + Debug.println("ERROR AdminServerProduct.getTargetAdminServerID: could not get product DN."); + return null; + } + entry = ldc.read(productDN); + if (entry == null) { + Debug.println( + "ERROR AdminServerProduct.getTargetAdminServerID: could not get entry = " + + productDN); + return null; + } + serverDN = LDAPUtil.flatting( entry.getAttribute("uniquemember", + LDAPUtil.getLDAPAttributeLocale())); + if (serverDN != null && serverDN.length() > 3) { + serverName = serverDN.substring(3, serverDN.indexOf(',')); + } + } + catch (LDAPException e) { + Debug.println( + "ERROR AdminServerProduct.getTargetAdminServerID: " + e); + return null; + } + + return serverName; + } + + + /* protected boolean migrateKeyCert(String serverRoot) { + String adminURL = _consoleInfo.getAdminURL(); + + String adminConfigFile = _keyCert.getConfigFile(); + if (adminConfigFile == null || adminConfigFile.equals("")) { + Debug.println("ERROR AdminServerProduct.migrateKeyCert: no admin config file"); + return false; + } + + String newAlias = _keyCert.getNewAlias(); + if (newAlias == null || newAlias.equals("")) { + Debug.println("ERROR AdminServerProduct.migrateKeyCert: no new key alias"); + return false; + } + + String password = _keyCert.getPassword(); + if (password == null || password.equals("")) { + Debug.println("ERROR AdminServerProduct.migrateKeyCert: no password"); + return false; + } + f + String commandString = new String(adminURL + "admin-serv/tasks/configuration/KeyCertMigration"); + Hashtable args = new Hashtable(); + args.put("conf_file", adminConfigFile); + args.put("newAlias", newAlias); + args.put("password", password); + Debug.println("TRACE AdminServerProduct.migrateKeyCert: migrate encryption commandString = " + commandString); + + try { + URL command = new URL(commandString); + AdmTask task = new AdmTask(command, + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + task.setArguments(args); + int execStatus = task.exec(); + if (execStatus != 0) { + Debug.println("ERROR AdminServerProduct.migrateKeyCert: exec failed"); + return false; + } + int status = task.getStatus(); + if (status != 0) { + Debug.println("ERROR AdminServerProduct.migrateKeyCert: exec status: " + status + ": " + task.getResult("NMC_ErrInfo")); + return false; + } + } + catch (MalformedURLException e) { + Debug.println("ERROR AdminServerProduct.migrateKeyCert: Bad URL: " + e); + return false; + } + catch (Exception e) { + Debug.println("ERROR AdminServerProduct.migrateKeyCert: unhandled exception: " + e); + return false; + } + + Debug.println("TRACE AdminServerProduct.migrateKeyCert: migrate key cert succeeded!"); + return true; + }*/ +} diff --git a/src/com/netscape/management/admserv/LoggingNode.java b/src/com/netscape/management/admserv/LoggingNode.java new file mode 100644 index 0000000..b008fdf --- /dev/null +++ b/src/com/netscape/management/admserv/LoggingNode.java @@ -0,0 +1,147 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.tree.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.logging.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.admserv.logging.*; +import netscape.ldap.*; + +public class LoggingNode extends ResourceObject implements IMenuInfo { + + static ResourceSet _resource = new ResourceSet("com.netscape.management.admserv.admserv"); + static RemoteImage _logFolderIcon = + new RemoteImage(_resource.getString("log", "FolderIcon")); + static RemoteImage _logFileIcon = + new RemoteImage(_resource.getString("log", "FileIcon")); + + private ConsoleInfo _ci; + + private BaseConfigPanel _configPanel; + + static public String MENU_CONFIG = "CONFIG"; + + private boolean _menuConfigEnabled; + + public LoggingNode(ConsoleInfo ci, String[] taskList) { + _ci = ci; + + //If a task is not visible to the user, then it should not be accessable + //from the resorce tree + _menuConfigEnabled = findTask("task.Logging", taskList); + + setName(_resource.getString("resourcepage","Logs")); + setIcon(_logFolderIcon); + + setAllowsChildren(true); // folder + add(new AccessLogNode(ci)); + add(new ErrorLogNode(ci)); + + } + + private boolean findTask(String task, String[] list) { + for (int i = 0; i < list.length; i++) { + if (list[i].endsWith(task)) + return true; + } + return false; + } + + public String[] getMenuCategoryIDs() { + return new String[]{ ResourcePage.MENU_OBJECT, + ResourcePage.MENU_CONTEXT }; + } + + public IMenuItem[] getMenuItems(String categoryID) { + if ((categoryID.equals(ResourcePage.MENU_OBJECT)) || + (categoryID.equals(ResourcePage.MENU_CONTEXT))) { + String i18nMenuConfig = _resource.getString("menu", "Config"); + String i18nDescrMenuConfig = + _resource.getString("menuDescription", "ConfigAdmin"); + + return new IMenuItem[]{ new MenuItemSeparator(), + new MenuItemText(MENU_CONFIG, i18nMenuConfig, + i18nDescrMenuConfig, _menuConfigEnabled)}; + } + return null; + } + + public void actionMenuSelected(IPage viewInstance, IMenuItem item) { + if (viewInstance instanceof ResourcePage) { + if (item.getID().equals(MENU_CONFIG)) { + ResourcePage page = (ResourcePage) viewInstance; + _configPanel = null; + page.setCustomPanel(getCustomPanel()); + } else { + Debug.println("Not Yet Implemented: " + item); + } + } + } + + + public Component getCustomPanel() { + if (!_menuConfigEnabled) + return null; + + if (_configPanel == null || !_configPanel.isInitialized()) { + _configPanel = + new BaseConfigPanel(new LoggingConfigPanel("", _ci)); + } + return _configPanel; + } + +} +class AccessLogNode extends ResourceObject { + ConsoleInfo _ci; + + public AccessLogNode(ConsoleInfo ci) { + _ci = ci; + setName(LoggingNode._resource.getString("resourcepage","LogAccess")); + setIcon(LoggingNode._logFileIcon); + } + + public Component getCustomPanel() { + return new LogViewer(new AccessLogViewerModel(_ci, "admin-serv/tasks/Configuration/ReadLog")); + } +} + +class ErrorLogNode extends ResourceObject { + ConsoleInfo _ci; + + public ErrorLogNode(ConsoleInfo ci) { + _ci = ci; + setName(LoggingNode._resource.getString("resourcepage","LogError")); + setIcon(LoggingNode._logFileIcon); + } + + public Component getCustomPanel() { + return new LogViewer(new ErrorLogViewerModel(_ci, "admin-serv/tasks/Configuration/ReadLog")); + } +} diff --git a/src/com/netscape/management/admserv/SNMPNode.java b/src/com/netscape/management/admserv/SNMPNode.java new file mode 100644 index 0000000..1eab71c --- /dev/null +++ b/src/com/netscape/management/admserv/SNMPNode.java @@ -0,0 +1,160 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.tree.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; +import com.netscape.management.admserv.config.*; +import netscape.ldap.*; + + +public class SNMPNode extends ResourceObject implements IMenuInfo { + + public static ResourceSet _resource; + public static String _i18nMenuConfig, _i18nMenuRestart, _i18nMenuStop; + public static String _i18nDescrMenuConfig, _i18nDescrMenuRestart, + _i18nDescrMenuStop; + public static String _i18nDialogTitleRestart, _i18nDialogTitleStop, + _i18nSNMPMasterAgent; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.admserv"); + _i18nMenuConfig = _resource.getString("menu", "Config"); + _i18nMenuRestart = _resource.getString("menu", "Restart"); + _i18nMenuStop = _resource.getString("menu", "Stop"); + _i18nDescrMenuConfig = _resource.getString("menuDescription", "ConfigSNMP"); + _i18nDescrMenuRestart = + _resource.getString("menuDescription", "RestartSNMP"); + _i18nDescrMenuStop = _resource.getString("menuDescription", "StopSNMP"); + _i18nDialogTitleStop = _resource.getString("taskDescription", "SNMPStop"); + _i18nDialogTitleRestart = + _resource.getString("taskDescription", "SNMPRestart"); + _i18nSNMPMasterAgent = _resource.getString("taskName", "SNMPMasterAgent"); + } + + static public String MENU_CONFIG = "CONFIG"; + static public String MENU_RESTART = "RESTART"; + static public String MENU_STOP = "STOP"; + + private ConsoleInfo _consoleInfo; + private BaseConfigPanel _configPanel; + private boolean _menuConfigEnabled; + + + public SNMPNode(ConsoleInfo ci, String[] taskList) { + super(_i18nSNMPMasterAgent); + _consoleInfo = ci; + + //If a task is not visible to the user, then it should not be accessable + //from the resorce tree + _menuConfigEnabled = findTask("task.SNMPSetup", taskList); + + setAllowsChildren(false); + } + + + private boolean findTask(String task, String[] list) { + for (int i = 0; i < list.length; i++) { + if (list[i].endsWith(task)) + return true; + } + return false; + } + + public Icon getIcon() { + return null; + } + + public String[] getMenuCategoryIDs() { + return new String[]{ ResourcePage.MENU_OBJECT, + ResourcePage.MENU_CONTEXT }; + } + + public IMenuItem[] getMenuItems(String categoryID) { + return new IMenuItem[]{ new MenuItemSeparator(), + new MenuItemText(MENU_CONFIG, _i18nMenuConfig, + _i18nDescrMenuConfig, _menuConfigEnabled), + new MenuItemText(MENU_RESTART, _i18nMenuRestart, + _i18nDescrMenuRestart, _menuConfigEnabled), + new MenuItemText(MENU_STOP, _i18nMenuStop, + _i18nDescrMenuStop, _menuConfigEnabled)}; + } + + public void actionMenuSelected(IPage viewInstance, IMenuItem item) { + if (viewInstance instanceof ResourcePage) { + if (item.getID().equals(MENU_CONFIG)) { + ResourcePage page = (ResourcePage) viewInstance; + _configPanel = null; + page.setCustomPanel(getCustomPanel()); + } else if (item.getID().equals(MENU_STOP)) { + String taskURL = "admin-serv/tasks/Operation/SNMPControl?ACTION=STOP"; + ResourcePage page = (ResourcePage) viewInstance; + AdminOperation operation = + new AdminOperation(_consoleInfo, taskURL); + operation.monitorOperation(""); + //page.setCustomPanel(operation.getPanel()); + String title = _i18nDialogTitleStop; + DialogFrame dialog = new DialogFrame(page, title, + operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + } else if (item.getID().equals(MENU_RESTART)) { + String taskURL = "admin-serv/tasks/Operation/SNMPControl?ACTION=RESTART"; + ResourcePage page = (ResourcePage) viewInstance; + AdminOperation operation = + new AdminOperation(_consoleInfo, taskURL); + operation.monitorOperation(""); + //page.setCustomPanel(operation.getPanel()); + String title = _i18nDialogTitleRestart; + DialogFrame dialog = new DialogFrame(page, title, + operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + } else { + Debug.println("Not Yet Implemented: " + item); + } + } + } + + /** + * return the host information panel to the caller + */ + public Component getCustomPanel() { + if (!_menuConfigEnabled) + return null; + + if (_configPanel == null || !_configPanel.isInitialized()) { + _configPanel = new BaseConfigPanel( + new SNMPConfigPanel(_consoleInfo)); + } + + return _configPanel; + } +} diff --git a/src/com/netscape/management/admserv/admserv.properties b/src/com/netscape/management/admserv/admserv.properties new file mode 100644 index 0000000..254c58d --- /dev/null +++ b/src/com/netscape/management/admserv/admserv.properties @@ -0,0 +1,143 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# + +# END COPYRIGHT BLOCK +# Admin Server Component Localization file + +admin-title=Administration Server +admin-version=Version 1.0.2 +admin-smallIcon=com/netscape/management/admserv/images/AdminServer.gif +admin-largeIcon=com/netscape/management/admserv/images/AdminServerL.gif + +error-OpenServerTitle=Open Server +error-CanNotOpenServer=Cannot open:\n{0} is DOWN. + +status-migrateTitle=Server Migration Status +status-migrateSucceeded=Server migration succeeded.\n\nThe server must be restarted before the\nconfiguration changes can take effect. +status-migrateConfigFailed=Could not migrate the server configuration. +status-migrateKeyCertFailed=Could not migrate the server key and certificate. + +status-cloneTitle=Server Cloning Status +status-cloneSucceeded=Server cloning to {0} succeeded. +status-cloneFailed=Server cloning to {0} failed. + +restart-mustRestart=The server must be restarted because of configuration changes. +restart-title=Restart Required +stop-ack=Once the Administration Server is stopped, it can not be started remotely\nfrom the Console.\n\nAre you sure you want to stop the server?\n\n + +log-FolderIcon=com/netscape/management/client/images/logfolder.gif +log-FileIcon=com/netscape/management/client/images/log.gif + +menu-Edit=Edit +menu-EditUndo=Undo +menu-EditCut=Cut +menu-EditCopy=Copy +menu-EditPaste=Paste +menu-EditDelete=Delete +menu-EditFindUG=Find Users or Groups +menu-EditPreferences=Preferences... +menu-EditSetACL=Set Access Permissions... + +menu-HelpAdminServer=Admin Server +menubar-adminserverHelpToken=framework-menubar-web-adminserver + +menu-Start=Start +menu-Restart=Restart +menu-Stop=Stop +menu-Open=Open +menu-Properties=Properties +menu-Operations=Operations +menu-Config=Configure... + +menuDescription-ConfigAdmin=Configure Admin Server, reload all data +menuDescription-RestartAdmin=Resart Admin Server +menuDescription-StopAdmin=Stop Admin Server +menuDescription-ConfigSNMP=Configure SNMP Master Agent, reload all data +menuDescription-RestartSNMP=Restart SNMP Master Agent +menuDescription-StopSNMP=Stop SNMP Master Agent + +dialog-configtitle=Administration Server Configuration + +resourcepage-Tasks=Tasks +resourcepage-Logs=Logs +resourcepage-LogAccess=Accesses +resourcepage-LogError=Errors +resourcepage-nodeDisplayName=Administration Server + + +taskpage-TasksList=Tasks List + +taskName-access=Superuser Settings +taskName-network=Network Settings +taskName-encryption=Encryption Preferences +taskName-logging=Logging Options +taskName-CertSetup=Manage Certificates +taskName-stop=Stop Server +taskName-restart=Restart Server +taskName-serverSetup=Configure Admin Server +taskName-SNMPSetup=Configure SNMP Master Agent +taskName-SNMPMasterAgent=SNMP Master Agent + +taskDescription-access=Description for superuser settings. +taskDescription-network=Description for network settings. +taskDescription-encryption=Description for encryption settings. +taskDescription-logging=Set Logging Options for this Administration Server. +taskDescription-CertSetup=Manage Certificates for this Administration Server. +taskDescription-stop=Stop this instance of the Administration Server. +taskDescription-restart=Restart this instance of the Administration Server. +taskDescription-serverSetup=Configure settings for this instance of the Administration Server. +taskDescription-SNMPSetup=Configure SNMP Master Agent settings for this instance of the Administration Server. +taskDescription-SNMPRestart=Restart SNMP Master Agent +taskDescription-SNMPStop=Stop SNMP Master Agent + +restart-canNotRestart=The Administration Server cannot be restarted remotely from the Console.\nThe server can be restarted only locally from the command shell\nby running the "restart-admin" command. + +# +# information panel +# +infopanel-ServerIcon=com/netscape/management/client/images/AdminServerL.gif +infopanel-NetscapeAdminServer=Administration Server +infopanel-ServerStatus=Server Status +infopanel-OpenServerButton=Open Server... +infopanel-OpenServerDescription=Click here to access Tasks and\nSettings for the highlighted Server +infopanel-ServerStatusUnknown=Server Status Unknown +infopanel-ServerInformation=Server Information +infopanel-VersionNumber=Version Number: +infopanel-InstallationDate=Installation Date: +infopanel-AdminURL=Admin URL +infopanel-Port=Port +infopanel-ServerOn=Server On +infopanel-ServerOff=Server Off + +help-configdialog=admin + +# +# Log Column Names +# +log-lineno=# +log-host=Host +log-username=Username +log-date=Date +log-time=Time +log-header=Header +log-errorcode=HTTP Code +log-length=Length +log-severity=Severity +log-details=Details diff --git a/src/com/netscape/management/admserv/classes.env b/src/com/netscape/management/admserv/classes.env new file mode 100644 index 0000000..c4385b3 --- /dev/null +++ b/src/com/netscape/management/admserv/classes.env @@ -0,0 +1,48 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# + +# END COPYRIGHT BLOCK +# +# Class Loader environment definition file +# +# admserv70.jar +# +# You can assume that the underlying default +# class loader contains an LDAP jdk jar, and +# any allowed SSL jars. Since these jars +# pledge backwards compatibility, they need +# not be specified as includes. +# +# Also note that including file.jar implicitly +# includes file_language.jar, where language +# is the ISO two character language code. +# +# Included files will be searched for in the jars +# subdirectory. The include directives need to be +# ordered sequencially, without skipping any +# numbers. The algorithm will read include directives +# until the first include-jar(N++) is not found. +# +#jdk-version=1.2.2 not used? too obsolete. the current version is 1.4.2! +#jfc-version=1.1.1 not used? +mcc-version=1.0 +#include-jar0= +#include-jar1= +#backward-compatible= diff --git a/src/com/netscape/management/admserv/cmdln/AdmpwTask.java b/src/com/netscape/management/admserv/cmdln/AdmpwTask.java new file mode 100644 index 0000000..34869f0 --- /dev/null +++ b/src/com/netscape/management/admserv/cmdln/AdmpwTask.java @@ -0,0 +1,118 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.cmdln; + + +import java.util.Vector; +import java.net.URL; +import com.netscape.management.client.util.AdmTask; +import com.netscape.management.client.util.AdmTaskArg; +import com.netscape.management.client.util.Debug; + + +/** + * Utility class to execute the count log entries task. + * + * @author Peter Lee + * @version %I%, %G% + * @see AdmTask + */ + +public class AdmpwTask extends AdmTask { + + private int _status; + + /** + * Constructor to build a task url. + * + * @param url the task url + * @param userID either username or user's DN String + * @param userPassword password of the users + */ + public AdmpwTask(URL url, String userID, String userPassword) { + + super(url, userID, userPassword); + _status = 0; // Default to success. + } + + + /** + * Constructor to build a task url. + * + * @param admProtocol protocol used by the target Admin Server (http/https) + * @param admServ host name of the target Admin Server + * @param admPort port number of the target Admin Server + * @param serverID name of the server which task will apply to + * @param taskID task name to be executed + * @param args arguments for the task + * @param userID either username or user's DN String + * @param userPassword password of the user + */ + public AdmpwTask(String admProtocol, String admServ, int admPort, + String serverID, String taskID, Vector args, + String userID, String userPassword) { + + super(admProtocol, admServ, admPort, serverID, taskID, args, + userID, userPassword); + _status = 0; // Default to success. + } + + + /** + * Parsing specific to the tasks involving the admpw CGI. + * + * @param s the input data line to be parsed + */ + public void parse(String s) { + //Debug.println("TRACE AdmpwTask.parse: " + s); + + int index; + if ((index = s.indexOf(":")) != (-1)) { + // This implies an error occurred. Look at the ReadLog.c CGI. + String name = s.substring(0, index).trim(); + String value = s.substring(index + 1).trim(); + if (name.equalsIgnoreCase("NMC_Status")) { + _status = Integer.parseInt(value); + addResponseArgument(new AdmTaskArg("NMC_ErrInfo", "Internal Error")); + } else { + addResponseArgument(new AdmTaskArg(name, value)); + } + } else { + _status = 1; + addResponseArgument(new AdmTaskArg("NMC_ErrInfo", "Internal Error")); + } + } + + + /** + * Status specific to the tasks involving the admpw CGI. + * Need to return superclass's getStatus in case exec failed! + * + * @return the integer result of running the task + */ + public int getStatus() { + if (_status != 0) { + return _status; + } else { + return super.getStatus(); + } + } +} diff --git a/src/com/netscape/management/admserv/cmdln/CommandLine.java b/src/com/netscape/management/admserv/cmdln/CommandLine.java new file mode 100644 index 0000000..3af5a9f --- /dev/null +++ b/src/com/netscape/management/admserv/cmdln/CommandLine.java @@ -0,0 +1,1739 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.cmdln; + + +import java.io.File; +import java.io.FileDescriptor; +import java.io.FileReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.BufferedReader; +import java.io.IOException; +import java.net.URL; +import java.net.URLEncoder; +import java.util.Locale; +import java.util.Hashtable; +import java.util.Vector; +import java.util.StringTokenizer; +import com.netscape.management.client.cmd.CommandLineParser; +import com.netscape.management.client.util.AdmTask; +import com.netscape.management.client.util.URLByteEncoder; +import com.netscape.management.client.util.Debug; + + +/** + * Netscape Admin Server Command Line (admconfig). + * + * @author Peter Lee (phlee@netscape.com) + * @version %I%, %G% + * @see CommandLineParser + * @see CountLogEntriesTask + * @see ViewLogEntriesTask + * @see AdmpwTask + */ + +public class CommandLine extends Object { + + // Needed to run multiple tasks from a single invocation. + protected static String[]_fileArgs = null; + protected static CommandLineParser _fileOpt = null; + protected static CommandLineParser _opt = null; + + + /** + * Starting point for Netscape Admin Server Command Line (admconfig). + * The CommandLine constructor parses all arguments to admconfig, and + * the run invocations task the server using AdmTask. + * + * @param args an array of strings representing the command line + * arguments + */ + static public void main(String[] args) { + //Debug.setTrace(true); + CommandLine cl = new CommandLine(args); + cl.run(_fileOpt, _fileArgs, false); // Invoke tasks specified in a file first + cl.run(_opt, args, true); // Invoke tasks specified on the command line + System.exit(0); // Return success! + } + + + + // Task Codes + protected static final int TC_SHOW_HELP = 0; + protected static final int TC_RESTART = 1; + protected static final int TC_STOP = 2; + protected static final int TC_GET_SYSTEM_USER = 3; + protected static final int TC_SET_SYSTEM_USER = 4; + protected static final int TC_GET_PORT = 5; + protected static final int TC_SET_PORT = 6; + protected static final int TC_GET_ADMINUSERS = 7; + protected static final int TC_SET_ADMINUSERS = 8; + protected static final int TC_GET_ERRORLOG = 9; + protected static final int TC_SET_ERRORLOG = 10; + protected static final int TC_GET_ACCESSLOG = 11; + protected static final int TC_SET_ACCESSLOG = 12; + protected static final int TC_GET_HOSTS = 13; + protected static final int TC_SET_HOSTS = 14; + protected static final int TC_GET_ADDRESSES = 15; + protected static final int TC_SET_ADDRESSES = 16; + protected static final int TC_GET_ONEACLDIR = 17; + protected static final int TC_SET_ONEACLDIR = 18; + protected static final int TC_GET_DEFAULTACCEPTLANGUAGE = 19; + protected static final int TC_SET_DEFAULTACCEPTLANGUAGE = 20; + protected static final int TC_GET_CLASSNAME = 21; + protected static final int TC_SET_CLASSNAME = 22; + protected static final int TC_COUNT_ERRORLOG_ENTRIES = 23; + protected static final int TC_VIEW_ERRORLOG_ENTRIES = 24; + protected static final int TC_COUNT_ACCESSLOG_ENTRIES = 25; + protected static final int TC_VIEW_ACCESSLOG_ENTRIES = 26; + protected static final int TC_ENABLE_ENDUSER_ACCESS = 27; + protected static final int TC_DISABLE_ENDUSER_ACCESS = 28; + protected static final int TC_ENABLE_DSGW_ACCESS = 29; + protected static final int TC_DISABLE_DSGW_ACCESS = 30; + protected static final int TC_GET_ADMIN_UID = 31; + protected static final int TC_SET_ADMIN_UID = 32; + protected static final int TC_SET_ADMIN_PWD = 33; + protected static final int TC_GET_DSCONFIG = 34; + protected static final int TC_SET_DSCONFIG = 35; + protected static final int TC_GET_CACHE_LIFETIME = 36; + protected static final int TC_SET_CACHE_LIFETIME = 37; + protected static final int TC_GET_SERVER_ADDRESS = 38; + protected static final int TC_SET_SERVER_ADDRESS = 39; + protected static final int TC_GET_UGDSCONFIG = 40; + protected static final int TC_SET_UGDSCONFIG = 41; + + // Help file names + protected static final String[]_admconfigHelpLookup = { "[help-main]", + "[help-restart]", "[help-stop]", "[help-getsystemuser]", + "[help-setsystemuser]", "[help-getport]", "[help-setport]", + "[help-getadminusers]", "[help-setadminusers]", "[help-geterrorlog]", + "[help-seterrorlog]", "[help-getaccesslog]", "[help-setaccesslog]", + "[help-gethosts]", "[help-sethosts]", "[help-getaddresses]", + "[help-setaddresses]", "[help-getoneacldir]", "[help-setoneacldir]", + "[help-getdefaultacceptlanguage]", "[help-setdefaultacceptlanguage]", + "[help-getclassname]", "[help-setclassname]", "[help-counterrorlogentries]", + "[help-viewerrorlogentries]", "[help-countaccesslogentries]", + "[help-viewaccesslogentries]", "[help-enableenduseraccess]", + "[help-disableenduseraccess]", "[help-enabledsgwaccess]", + "[help-disabledsgwaccess]", "[help-getadminuid]", "[help-setadminuid]", + "[help-setadminpwd]", "[help-getdsconfig]", "[help-setdsconfig]", + "[help-getcachelifetime]", "[help-setcachelifetime]", "[help-getserveraddress]", + "[help-setserveraddress]", "[help-getugdsconfig]", "[help-setugdsconfig]" }; + + // Task names + protected static final String[]_admconfigTaskLookup = { "-restart", + "-stop", "-getsystemuser", "-setsystemuser", "-getport", + "-setport", "-getadminusers", "-setadminusers", "-geterrorlog", + "-seterrorlog", "-getaccesslog", "-setaccesslog", "-gethosts", + "-sethosts", "-getaddresses", "-setaddresses", "-getoneacldir", + "-setoneacldir", "-getdefaultacceptlanguage", "-setdefaultacceptlanguage", + "-getclassname", "-setclassname", "-counterrorlogentries", + "-viewerrorlogentries", "-countaccesslogentries", "-viewaccesslogentries", + "-enableenduseraccess", "-disableenduseraccess", "-enabledsgwaccess", + "-disabledsgwaccess", "-getadminuid", "-setadminuid", "-setadminpwd", + "-getdsconfig", "-setdsconfig", "-getcachelifetime", "-setcachelifetime", + "-getserveraddress", "-setserveraddress", "-getugdsconfig", + "-setugdsconfig" }; + + // Option Control String Codes + protected static final int OPT_ENCRYPTION = 0; + protected static final int OPT_HELP = 1; + protected static final int OPT_INPUT_FILE = 2; + protected static final int OPT_QUIET_LEVEL = 3; + protected static final int OPT_SERVER = 4; + protected static final int OPT_USER = 5; + protected static final int OPT_VERSION = 6; + protected static final int OPT_CONTINUE_ON_ERROR = 7; + protected static final int OPT_TASKS_OFFSET = 7; + + // Option Control strings. These are different than the task names! + protected static final String[]_admconfigControlStrings = { "-encryption", + "-help:", "-inputfile:", "-verbose:", "-server:", "-user:", + "-version", "-continueonerror", "-restart", "-stop", "-getsystemuser", + "-setsystemuser:", "-getport", "-setport:", "-getadminusers", + "-setadminusers:", "-geterrorlog", "-seterrorlog:", "-getaccesslog", + "-setaccesslog:", "-gethosts", "-sethosts:", "-getaddresses", + "-setaddresses:", "-getoneacldir", "-setoneacldir:", "-getdefaultacceptlanguage", + "-setdefaultacceptlanguage:", "-getclassname", "-setclassname:", + "-counterrorlogentries", "-viewerrorlogentries:", "-countaccesslogentries", + "-viewaccesslogentries:", "-enableenduseraccess", "-disableenduseraccess", + "-enabledsgwaccess", "-disabledsgwaccess", "-getadminuid", + "-setadminuid:", "-setadminpwd:", "-getdsconfig", "-setdsconfig:", + "-getcachelifetime", "-setcachelifetime:", "-getserveraddress", + "-setserveraddress:", "-getugdsconfig", "-setugdsconfig:" }; + + + protected static final String PACKAGE_DIR = "com/netscape/management/admserv/cmdln"; + protected static final String RESTART_TASK = "admin-serv/tasks/operation/Restart"; + protected static final String STOP_TASK = "admin-serv/tasks/operation/Stop"; + protected static final String READ_LOG_TASK = "admin-serv/tasks/configuration/ReadLog"; + protected static final String SERVER_SETUP_TASK = "admin-serv/tasks/configuration/ServerSetup"; + protected static final String ACCESS_SETUP_TASK = "admin-serv/tasks/configuration/AccessSetup"; + protected static final String DIRECTORY_SETUP_TASK = "admin-serv/tasks/configuration/DirectorySetup"; + protected static final String UG_DIRECTORY_SETUP_TASK = "admin-serv/tasks/configuration/UGDirectorySetup"; + protected static final String DATA_FILE = "admconfig.dat"; + protected static final String VERSION_FILE = "version.dat"; + + + protected String _protocol; // "http" or "https" depending on -e option + protected String _server; // "hostname:port" combination + protected String _admin; // administrator username + protected String _password; // administrator password + protected int _tc; // task code + protected String _task; // user entered task string + protected String _inputFile; // input file + protected int _verbose; // screen message output level: + // (9=detailed, 0=none) + protected String _newValue; // new value + protected boolean _quitOnError; + + + //task that require restart to take effect + //-setAdminUID, -setAdminPwd, -setAdminUsers, -setDSConfig, -setPort, + //-setSystemUser, -setUGDSConfig + private void printRestartMessage() { + System.out.println("\nRestart the Admin Server for the changes to take effect."); + } + + + /** + * Constructor parses the command line arguments for admconfig. Since + * different options cause admconfig to run differently, there is an + * order of precedence for which option is "evaluated" first. + *

+ * The first option that is checked is the -inputfile option for the + * input file containing additional arguments. After the option file is + * read in to a String, the arguments within the file are parsed exactly + * the same way as the arguments supplied on the command line. + *

+ * The next option checked is the -help option for help. If there is + * -help anywhere in the command line argument, then help is displayed + * and admconfig exits. For example, admconfig -version -help + * will result only in the help being displayed. + *

+ * The next option checked is the -version option for version information. + * If there is -version anywhere in the argument list, then the version + * information is displayed and admconfig exits. The only exception is in + * the aforementioned case for -help. + *

+ * The remaining admconfig options determine the parameters for the + * server managing tasks. If there are duplicate information for an + * option, for example, + * admconfig -server jaffer:31044 -server nugget:33333 ..., + * the last instance of the option (nugget:33333) is used. + * + * @param args Command line arguments. + */ + public CommandLine(String[] args) { + + if (args.length < 1) { + showHelp(_admconfigHelpLookup[TC_SHOW_HELP]); + System.exit(0); + } + + // Parse the arguments into various options. + _opt = new CommandLineParser(_admconfigControlStrings, args); + + _protocol = "http"; // Use regular protocol by default. + _tc = TC_SHOW_HELP; + _verbose = 5; + _quitOnError = true; + + // Parse arguments provided in a file, if any. + handleInputFile(_opt, args); + + // Parse the remaining arguments. Note that if there are + // repeated arguments, the arguments in the _inputFile may + // be overridden by ones on the command line. Since this + // parses the remaining arguments, the required arguments + // must be found, as indicated by the boolean parameter. + // If the required arguments are not found, display usage + // information and exit. + parseArguments(_opt, args, true); + } + + + + /** + * Determines which tasks to run on the server. Supports running + * multiple tasks during this instance of the command line. Reuses + * options such as the server and user information. If the + * taskRequired flag is true, then at + * least one valid task must have been run or must be about to run. + * + * @param taskOpt the CommandLineParser object to parse the taskArgs + * @param taskArgs an array of String arguments containing the tasks + * @param taskRequired a boolean flag indicating whether the task must be specified + */ + public void run(CommandLineParser taskOpt, String[] taskArgs, + boolean taskRequired) { + + if ((taskOpt == null) || (taskArgs == null) || + (taskArgs.length == 0)) { + if (taskRequired == true) { + // Task must be specified! + System.err.println("ERROR admconfig:"); + System.err.println(" Task not specified."); + System.err.println(" Try admconfig -h for help on using admconfig.\n"); + System.exit(1); + } else { + return; // Simply return. + } + } + + int tc = TC_SHOW_HELP; + if (taskArgs != null) { + for (int i = 0; i < taskArgs.length; i++) { + _newValue = null; + tc = getTaskCode(taskArgs[i], false); // Don't want error messages for mismatches + switch (tc) { + case TC_SET_SYSTEM_USER: + case TC_SET_PORT: + case TC_SET_ADMINUSERS: + case TC_SET_ERRORLOG: + case TC_SET_ACCESSLOG: + case TC_SET_HOSTS: + case TC_SET_ADDRESSES: + case TC_SET_ONEACLDIR: + case TC_SET_DEFAULTACCEPTLANGUAGE: + case TC_SET_CLASSNAME: + case TC_VIEW_ERRORLOG_ENTRIES: + case TC_VIEW_ACCESSLOG_ENTRIES: + case TC_SET_ADMIN_UID: + case TC_SET_ADMIN_PWD: + case TC_SET_DSCONFIG: + case TC_SET_CACHE_LIFETIME: + case TC_SET_SERVER_ADDRESS: + // Make sure there is a parameter for the above tasks! + _newValue = taskOpt.getOptionParam( + _admconfigControlStrings[tc + + OPT_TASKS_OFFSET]); + if (_newValue == null) { + System.err.println("ERROR admconfig:"); + System.err.println(" Invalid number of parameters specified for task."); + showHelp(_admconfigHelpLookup[tc]); + if (_quitOnError) { + System.exit(1); + } else { + return; // Try the next valid task, if any. + } + } + break; // out of switch statement + case TC_SET_UGDSCONFIG: + // parameter is optional for this task + _newValue = taskOpt.getOptionParam( + _admconfigControlStrings[tc + + OPT_TASKS_OFFSET]); + break; // out of switch statement + default: + break; // out of switch statement + } + + if (TC_SHOW_HELP != tc) { + // Cannot write over last good value. We need it to determine + // whether at least one task was specified. + _tc = tc; + + // Display trace information if in full verbose mode. + if (9 == _verbose) { + System.out.println( + "\nadmconfig: about to run " + _task); + if (_newValue != null) { + System.out.println( + "admconfig: task arg: " + + _newValue); + } + } + + runTask(); // Task the server using AdmTask. + } + } + } + if ((true == taskRequired) && (TC_SHOW_HELP == _tc)) { + // Task must be specified! + System.err.println("ERROR admconfig:"); + System.err.println(" No valid task was specified."); + System.err.println(" Try admconfig -h for help on using admconfig.\n"); + System.exit(1); + } + } + + + /** + * Runs the task that has been determined from the run() + * method on the specified server. + */ + public void runTask() { + // Only need to encode arguments. HttpChannel already encodes + // username and password. + + try { + URL taskurl = null; + String encodedFilename = null; + StringTokenizer tokenizer = null; + String startToken = null; + String stopToken = null; + String dsHostToken = null; // Used for both dsconfig and ugdsconfig + String dsPortToken = null; // Used for both dsconfig and ugdsconfig + String dsBaseDNToken = null; // Used for ugdsconfig + String dsSSLFlagToken = null; // Used for both dsconfig and ugdsconfig + String dsSSLFlagResult = null; // Used for dsconfig + String dsBindDNToken = null; // Used for ugdsconfig + String dsBindPwdToken = null; // Used for ugdsconfig + String dsURL = null; // Used for ugdsconfig + int logStart = 0; + int logStop = 0; + int dsPort = 0; + int adminPort = 0; + int cacheLifetime = 0; + switch (_tc) { + case TC_RESTART: + taskurl = new URL(_protocol + "://" + _server + "/" + + RESTART_TASK + "?op=restart"); + break; + case TC_STOP: + taskurl = new URL(_protocol + "://" + _server + "/" + + STOP_TASK); + break; + case TC_GET_SYSTEM_USER: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nssuitespotuser") + + "="); + break; + case TC_SET_SYSTEM_USER: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nssuitespotuser") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_PORT: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsserverport") + + "="); + break; + case TC_SET_PORT: + adminPort = 0; + try { + adminPort = Integer.parseInt(_newValue); + } catch (NumberFormatException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " Specified server port is invalid: " + + _newValue); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsserverport") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_ADMINUSERS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsadminusers") + + "="); + break; + case TC_SET_ADMINUSERS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsadminusers") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_ERRORLOG: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nserrorlog") + + "="); + break; + case TC_SET_ERRORLOG: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nserrorlog") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_ACCESSLOG: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsaccesslog") + + "="); + break; + case TC_SET_ACCESSLOG: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsaccesslog") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_HOSTS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsadminaccesshosts") + + "="); + break; + case TC_SET_HOSTS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsadminaccesshosts") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_ADDRESSES: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsadminaccessaddresses") + + "="); + break; + case TC_SET_ADDRESSES: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsadminaccessaddresses") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_ONEACLDIR: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsadminoneacldir") + + "="); + break; + case TC_SET_ONEACLDIR: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsadminoneacldir") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_DEFAULTACCEPTLANGUAGE: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsdefaultacceptlanguage") + + "="); + break; + case TC_SET_DEFAULTACCEPTLANGUAGE: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsdefaultacceptlanguage") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_CLASSNAME: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsclassname") + + "="); + break; + case TC_SET_CLASSNAME: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsclassname") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_CACHE_LIFETIME: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsadmincachelifetime") + + "="); + break; + case TC_SET_CACHE_LIFETIME: + cacheLifetime = 0; + try { + cacheLifetime = Integer.parseInt(_newValue); + } catch (NumberFormatException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " Specified cache lifetime is invalid: " + + _newValue); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsadmincachelifetime") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_SERVER_ADDRESS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("configuration.nsserveraddress") + + "="); + break; + case TC_SET_SERVER_ADDRESS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("configuration.nsserveraddress") + + "=" + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_COUNT_ERRORLOG_ENTRIES: + encodedFilename = getLog("configuration.nserrorlog"); + if (encodedFilename == null) { + // We can simply return if null. The getLog method would + // have exited already if _quitOnError was true. + return; + } + taskurl = new URL(_protocol + "://" + _server + "/" + + READ_LOG_TASK + "?op=count&" + "name=" + + encodedFilename); + break; + case TC_VIEW_ERRORLOG_ENTRIES: + tokenizer = new StringTokenizer(_newValue); + if (tokenizer.countTokens() != 2) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " Invalid number of arguments for the task: " + + tokenizer.countTokens()); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // First token is the entry number to start displaying from. + startToken = tokenizer.nextToken(); + logStart = 0; + try { + logStart = Integer.parseInt(startToken); + } catch (NumberFormatException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " The entry number to start viewing is invalid: " + + startToken); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // Second token is the last entry number to display. + stopToken = tokenizer.nextToken(); + logStop = 0; + try { + logStop = Integer.parseInt(stopToken); + } catch (NumberFormatException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " The entry number to stop viewing is invalid: " + + stopToken); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + encodedFilename = getLog("configuration.nserrorlog"); + if (encodedFilename == null) { + // We can simply return if null. The getLog method would + // have exited already if _quitOnError was true. + return; + } + // Finally, set the task url. + taskurl = new URL(_protocol + "://" + _server + "/" + + READ_LOG_TASK + "?op=read&" + "name=" + + encodedFilename + "&start=" + startToken + + "&stop=" + stopToken); + break; + case TC_COUNT_ACCESSLOG_ENTRIES: + encodedFilename = getLog("configuration.nsaccesslog"); + if (encodedFilename == null) { + // We can simply return if null. The getLog method would + // have exited already if _quitOnError was true. + return; + } + taskurl = new URL(_protocol + "://" + _server + "/" + + READ_LOG_TASK + "?op=count&" + "name=" + + encodedFilename); + break; + case TC_VIEW_ACCESSLOG_ENTRIES: + tokenizer = new StringTokenizer(_newValue); + if (tokenizer.countTokens() != 2) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " Invalid number of arguments for the task: " + + tokenizer.countTokens()); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // First token is the entry number to start displaying from. + startToken = tokenizer.nextToken(); + logStart = 0; + try { + logStart = Integer.parseInt(startToken); + } catch (NumberFormatException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " The entry number to start viewing is invalid: " + + startToken); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // Second token is the last entry number to display. + stopToken = tokenizer.nextToken(); + logStop = 0; + try { + logStop = Integer.parseInt(stopToken); + } catch (NumberFormatException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " The entry number to stop viewing is invalid: " + + stopToken); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + encodedFilename = getLog("configuration.nsaccesslog"); + if (encodedFilename == null) { + // We can simply return if null. The getLog method would + // have exited already if _quitOnError was true. + return; + } + // Finally, set the task url. + taskurl = new URL(_protocol + "://" + _server + "/" + + READ_LOG_TASK + "?op=read&" + "name=" + + encodedFilename + "&start=" + startToken + + "&stop=" + stopToken); + break; + case TC_ENABLE_ENDUSER_ACCESS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=force_set&" + + URLByteEncoder.encodeUTF8("configuration.nsadminenableenduser") + + "="); + break; + case TC_DISABLE_ENDUSER_ACCESS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=force_set&" + + URLByteEncoder.encodeUTF8("configuration.nsadminenableenduser") + + "=off"); + break; + case TC_ENABLE_DSGW_ACCESS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=force_set&" + + URLByteEncoder.encodeUTF8("configuration.nsadminenabledsgw") + + "="); + break; + case TC_DISABLE_DSGW_ACCESS: + taskurl = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=force_set&" + + URLByteEncoder.encodeUTF8("configuration.nsadminenabledsgw") + + "=off"); + break; + case TC_GET_ADMIN_UID: + taskurl = new URL(_protocol + "://" + _server + "/" + + ACCESS_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8("admpw.uid") + "="); + break; + case TC_SET_ADMIN_UID: + taskurl = new URL(_protocol + "://" + _server + "/" + + ACCESS_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("admpw.uid") + "=" + + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_SET_ADMIN_PWD: + taskurl = new URL(_protocol + "://" + _server + "/" + + ACCESS_SETUP_TASK + "?op=set&" + + URLByteEncoder.encodeUTF8("admpw.pw") + "=" + + URLByteEncoder.encodeUTF8(_newValue)); + break; + case TC_GET_DSCONFIG: + // The arguments are set below using the AdmTask.setArguments method. + taskurl = new URL(_protocol + "://" + _server + "/" + + DIRECTORY_SETUP_TASK); + break; + case TC_SET_DSCONFIG: + // The arguments are set below using the AdmTask.setArguments method. + taskurl = new URL(_protocol + "://" + _server + "/" + + DIRECTORY_SETUP_TASK); + tokenizer = new StringTokenizer(_newValue); + if (tokenizer.countTokens() != 3) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " Invalid number of arguments for the task: " + + tokenizer.countTokens()); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // First token is the dsconfig.host parameter. + dsHostToken = tokenizer.nextToken(); + // Second token is the dsconfig.port parameter. + dsPortToken = tokenizer.nextToken(); + dsPort = 0; + try { + dsPort = Integer.parseInt(dsPortToken); + } catch (NumberFormatException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " The dsconfig.port parameter is invalid: " + + dsPortToken); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // Third token is the dsconfig.ssl parameter. + dsSSLFlagToken = tokenizer.nextToken(); + if (dsSSLFlagToken.equalsIgnoreCase("true") == false && + dsSSLFlagToken.equalsIgnoreCase("false") == false) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " The dsconfig.ssl parameter is invalid: " + + dsSSLFlagToken); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + break; + case TC_GET_UGDSCONFIG: + // The arguments are set below using the AdmTask.setArguments method. + taskurl = new URL(_protocol + "://" + _server + "/" + + UG_DIRECTORY_SETUP_TASK); + break; + case TC_SET_UGDSCONFIG: + // The arguments are set below using the AdmTask.setArguments method. + taskurl = new URL(_protocol + "://" + _server + "/" + + UG_DIRECTORY_SETUP_TASK); + if (_newValue == null) { + break; + } + tokenizer = new StringTokenizer(_newValue); + if (tokenizer.countTokens() != 6) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " Invalid number of arguments for the task: " + + tokenizer.countTokens()); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // First token is the ugdsconfig.host parameter. + dsHostToken = tokenizer.nextToken(); + // Second token is the ugdsconfig.port parameter. + dsPortToken = tokenizer.nextToken(); + dsPort = 0; + try { + dsPort = Integer.parseInt(dsPortToken); + } catch (NumberFormatException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " The port parameter is invalid: " + + dsPortToken); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // Third token is the ugdsconfig.baseDN parameter. + dsBaseDNToken = tokenizer.nextToken(); + dsBaseDNToken = dsBaseDNToken.replace('+', ' '); + // Fourth token is the ssl parameter. + dsSSLFlagToken = tokenizer.nextToken(); + if (dsSSLFlagToken.equalsIgnoreCase("true") == false && + dsSSLFlagToken.equalsIgnoreCase("false") == false) { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println( + " The ssl parameter is invalid: " + + dsSSLFlagToken); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + // Fifth token is the ugdsconfig.binddn parameter. + dsBindDNToken = tokenizer.nextToken(); + dsBindDNToken = dsBindDNToken.replace('+', ' '); + // Sixth token is the ugdsconfig.bindpw parameter. + dsBindPwdToken = tokenizer.nextToken(); + dsBindPwdToken = dsBindPwdToken.replace('+', ' '); + break; + default: + System.err.println("ERROR admconfig:"); + System.err.println(" Invalid task specified = " + _tc); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + + AdmTask task; + // Some tasks require a specialized AdmTask. + switch (_tc) { + case TC_GET_ADMIN_UID: + case TC_SET_ADMIN_UID: + case TC_SET_ADMIN_PWD: + task = new AdmpwTask(taskurl, _admin, _password); + break; + case TC_COUNT_ERRORLOG_ENTRIES: + case TC_COUNT_ACCESSLOG_ENTRIES: + task = new CountLogEntriesTask(taskurl, _admin, _password); + break; + case TC_VIEW_ERRORLOG_ENTRIES: + case TC_VIEW_ACCESSLOG_ENTRIES: + task = new ViewLogEntriesTask(taskurl, _admin, _password); + break; + case TC_GET_DSCONFIG: + task = new AdmTask(taskurl, _admin, _password); + // Providing the arguments as part of the URL does not work with + // the DIRECTORY_SETUP_TASK CGI. + task.setArguments("op=getconfig"); + break; + case TC_SET_DSCONFIG: + task = new AdmTask(taskurl, _admin, _password); + // Providing the arguments as part of the URL does not work with + // the DIRECTORY_SETUP_TASK CGI. + task.setArguments("op=setconfig&" + + URLByteEncoder.encodeUTF8("dsconfig.host") + + "=" + URLEncoder.encode(dsHostToken) + "&" + + URLByteEncoder.encodeUTF8("dsconfig.port") + + "=" + dsPortToken + "&" + + URLByteEncoder.encodeUTF8("dsconfig.ssl") + + "=" + dsSSLFlagToken); + break; + case TC_GET_UGDSCONFIG: + task = new AdmTask(taskurl, _admin, _password); + // Providing the arguments as part of the URL does not work with + // the UG_DIRECTORY_SETUP_TASK CGI. + task.setArguments("op=getconfig"); + break; + case TC_SET_UGDSCONFIG: + task = new AdmTask(taskurl, _admin, _password); + // Providing the arguments as part of the URL does not work with + // the UG_DIRECTORY_SETUP_TASK CGI. + if (_newValue == null) { + task.setArguments("op=setconfig&" + + URLByteEncoder.encodeUTF8("ugdsconfig.inforef") + + "=" + URLByteEncoder.encodeUTF8("default")); + } else { + if (dsSSLFlagToken.equalsIgnoreCase("true")) { + dsURL = "ldaps://"+dsHostToken + ":"+ + dsPortToken + "/"+dsBaseDNToken; + } else { + dsURL = "ldap://"+dsHostToken + ":"+ + dsPortToken + "/"+dsBaseDNToken; + } + task.setArguments("op=setconfig&" + + URLByteEncoder.encodeUTF8("ugdsconfig.dirurl") + + "=" + URLByteEncoder.encodeUTF8(dsURL) + + "&" + URLByteEncoder.encodeUTF8("ugdsconfig.binddn") + + "=" + + URLByteEncoder.encodeUTF8(dsBindDNToken) + + "&" + URLByteEncoder.encodeUTF8("ugdsconfig.bindpw") + + "=" + + URLByteEncoder.encodeUTF8(dsBindPwdToken)); + } + break; + default: + task = new AdmTask(taskurl, _admin, _password); + break; + } + int execStatus = task.exec(); + if (execStatus != 0) { + System.err.println("Status = " + execStatus); + System.err.println(" exec failed for " + _task); + System.err.println(""); // Separate output for next command. + if (_quitOnError) { + System.exit(execStatus); + } else { + return; + } + } else { + int status = task.getStatus(); + if (status == 3 && (_tc == TC_RESTART || _tc == TC_STOP)) { + // Do nothing. This is okay. We get status == 3 for TC_RESTART and + // TC_STOP because the admin server process we were talking to has + // gone down (and restarted for TC_RESTART). + } else if (status != 0) { + System.err.println("Status = " + status); + System.err.println(" Task " + _task + + " failed: " + task.getResult("NMC_ErrInfo")); + System.err.println(""); // Separate output for next command. + if (_quitOnError) { + System.exit(status); + } else { + return; + } + } + + System.out.println("Task " + _task + + " succeeded with status = " + status); + switch (_tc) { + case TC_RESTART: + System.out.println(" Server has been restarted."); + System.out.println("\nWaiting 15 seconds for the server to come up before continuing."); + System.out.println("Press Ctrl-C to exit admconfig."); + Thread.sleep(15000); + break; + case TC_STOP: + System.out.println(" Server has been stopped."); + System.out.println("\nThe server must be started before any more tasks can be run.\n"); + System.exit(0); + break; + case TC_GET_SYSTEM_USER: + System.out.println( + " configuration.nssuitespotuser = " + + task.getResult("configuration.nssuitespotuser")); + break; + case TC_GET_PORT: + System.out.println( + " configuration.nsserverport = " + + task.getResult("configuration.nsserverport")); + break; + case TC_GET_ADMINUSERS: + System.out.println( + " configuration.nsadminusers = " + + task.getResult("configuration.nsadminusers")); + break; + case TC_GET_ERRORLOG: + System.out.println( " configuration.nserrorlog = " + + task.getResult("configuration.nserrorlog")); + break; + case TC_GET_ACCESSLOG: + System.out.println( " configuration.nsaccesslog = " + + task.getResult("configuration.nsaccesslog")); + break; + case TC_GET_HOSTS: + System.out.println( + " configuration.nsadminaccesshosts = " + + task.getResult("configuration.nsadminaccesshosts")); + break; + case TC_GET_ADDRESSES: + System.out.println( + " configuration.nsadminaccessaddresses = " + + task.getResult("configuration.nsadminaccessaddresses")); + break; + case TC_GET_ONEACLDIR: + System.out.println( + " configuration.nsadminoneacldir = " + + task.getResult("configuration.nsadminoneacldir")); + break; + case TC_GET_DEFAULTACCEPTLANGUAGE: + System.out.println( + " configuration.nsdefaultacceptlanguage = " + + task.getResult("configuration.nsdefaultacceptlanguage")); + break; + case TC_GET_CLASSNAME: + System.out.println( " configuration.nsclassname = " + + task.getResult("configuration.nsclassname")); + break; + case TC_GET_CACHE_LIFETIME: + System.out.println( + " configuration.nsadmincachelifetime = " + + task.getResult("configuration.nsadmincachelifetime")); + break; + case TC_GET_SERVER_ADDRESS: + System.out.println( + " configuration.nsserveraddress = " + + task.getResult("configuration.nsserveraddress")); + break; + case TC_COUNT_ERRORLOG_ENTRIES: + case TC_COUNT_ACCESSLOG_ENTRIES: + System.out.println(" count = " + + task.getResult("count")); + break; + case TC_VIEW_ERRORLOG_ENTRIES: + case TC_VIEW_ACCESSLOG_ENTRIES: + System.out.println(task.getResult("result")); + break; + case TC_ENABLE_ENDUSER_ACCESS: + System.out.println(" End user access has been enabled."); + break; + case TC_DISABLE_ENDUSER_ACCESS: + System.out.println(" End user access has been disabled."); + break; + case TC_ENABLE_DSGW_ACCESS: + System.out.println(" Directory Server Gateway access has been enabled."); + break; + case TC_DISABLE_DSGW_ACCESS: + System.out.println(" Directory Server Gateway access has been disabled."); + break; + case TC_GET_ADMIN_UID: + System.out.println(" admpw.uid = " + + task.getResult("admpw.uid")); + break; + case TC_GET_DSCONFIG: + System.out.println(" dsconfig.host = " + + task.getResult("dsconfig.host")); + System.out.println(" dsconfig.port = " + + task.getResult("dsconfig.port")); + dsSSLFlagResult = (String) task.getResult("dsconfig.ssl"); + if (dsSSLFlagResult == null || + dsSSLFlagResult.equalsIgnoreCase("false")) { + System.out.println(" dsconfig.ssl = false"); + } else { + System.out.println(" dsconfig.ssl = true"); + } + break; + case TC_GET_UGDSCONFIG: + System.out.println( " ugdsconfig.inforef = " + + task.getResult("ugdsconfig.inforef")); + System.out.println( " ugdsconfig.globaldirurl = " + + task.getResult("ugdsconfig.globaldirurl")); + System.out.println( " ugdsconfig.dirurl = " + + task.getResult("ugdsconfig.dirurl")); + System.out.println( " ugdsconfig.binddn = " + + task.getResult("ugdsconfig.binddn")); + //System.out.println(" ugdsconfig.bindpw = " + task.getResult("ugdsconfig.bindpw")); + break; + case TC_SET_SYSTEM_USER: + case TC_SET_PORT: + case TC_SET_ADMINUSERS: + case TC_SET_ERRORLOG: + case TC_SET_ACCESSLOG: + case TC_SET_HOSTS: + case TC_SET_ADDRESSES: + case TC_SET_ONEACLDIR: + case TC_SET_DEFAULTACCEPTLANGUAGE: + case TC_SET_CLASSNAME: + case TC_SET_CACHE_LIFETIME: + case TC_SET_SERVER_ADDRESS: + case TC_SET_ADMIN_UID: + case TC_SET_ADMIN_PWD: + case TC_SET_DSCONFIG: + case TC_SET_UGDSCONFIG: + break; + } + + switch (_tc) { + case TC_SET_PORT: + case TC_SET_ADMIN_UID: + case TC_SET_ADMIN_PWD: + case TC_SET_DSCONFIG: + case TC_SET_UGDSCONFIG: + case TC_SET_ADMINUSERS: + case TC_SET_SYSTEM_USER: + printRestartMessage(); + break; + } + + System.out.println(""); // Separate output for next command. + return; // Success! + } + } + catch (Exception e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Task " + _task + " caused an exception."); + System.err.println(" Exception: " + e); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return; + } + } + } + + + + /** + * Parse arguments using the provided parser. The argRequired + * parameter is used to determine whether a particular argument must be + * specified. This allows some options to be specified in a file. As a + * a fallback, all required options must be provided on the command + * line if an input file is not used. + * + * @param opt the CommandLineParser object for parsing args + * @param args an array of String arguments + * @param argRequired a boolean flag indicating whether the argument must be specified + */ + protected void parseArguments(CommandLineParser opt, String args[], + boolean argRequired) { + + // If help option was specified, display the help info and exit. + handleHelp(opt); + + // If version option was specified, display the version info and exit. + handleVersion(opt); + + if (opt.hasOption(_admconfigControlStrings[OPT_QUIET_LEVEL])) { + String verbose = opt.getOptionParam( + _admconfigControlStrings[OPT_QUIET_LEVEL]); + if (null == verbose) { + _verbose = 9; // Max level + } else { + try { + _verbose = Integer.parseInt(verbose); + } catch (NumberFormatException e) { + System.err.println("WARNING admconfig:"); + System.err.println( + " Parameter for -verbose option is not a number: " + + verbose); + System.err.println(" Setting verbose level to 9."); + _verbose = 9; + } + + if (_verbose < 0 || _verbose > 9) { + System.err.println("WARNING admconfig:"); + System.err.println(" Invalid level: " + _verbose); + System.err.println(" Setting verbose level to default value of 5."); + _verbose = 5; + } + } + + // Display trace information if in full verbose mode. + if (9 == _verbose) { + System.out.println("admconfig: verbose: " + + _verbose); + } + } + + if (opt.hasOption(_admconfigControlStrings[OPT_ENCRYPTION])) { + _protocol = "https"; + + // Display trace information if in full verbose mode. + if (9 == _verbose) { + System.out.println("admconfig: protocol: " + + _protocol); + } + } + + if (opt.hasOption( + _admconfigControlStrings[OPT_CONTINUE_ON_ERROR])) { + _quitOnError = false; + + // Display trace information if in full verbose mode. + if (9 == _verbose) { + System.out.println("admconfig: quit on error: " + + _quitOnError); + } + } + + if (opt.hasOption(_admconfigControlStrings[OPT_SERVER])) { + String serverInfo = opt.getOptionParam( + _admconfigControlStrings[OPT_SERVER]); + if (null == serverInfo) { + System.err.println("ERROR admconfig:"); + System.err.println(" Required parameter for the -server option was not specified."); + showHelp(_admconfigHelpLookup[TC_SHOW_HELP]); + System.exit(1); + } else { + // Use default localhost if none specified. + int colonIndex = serverInfo.indexOf(':'); + if ((-1 == colonIndex) || + ((colonIndex + 1) == serverInfo.length())) { + // Port is required field for now. + System.err.println("ERROR admconfig:"); + System.err.println(" Server port was not specified."); + System.err.println(" Try admconfig -h for help on using admconfig.\n"); + System.exit(1); + } + if (0 == colonIndex) { + _server = "localhost" + serverInfo; + } else { + _server = serverInfo; + } + } + + // Display trace information if in full verbose mode. + if (9 == _verbose) { + System.out.println("admconfig: server: " + + _server); + } + } + if ((true == argRequired) && (null == _server)) { + System.err.println("ERROR admconfig:"); + System.err.println(" Server name and port number were not specified."); + System.err.println(" Try admconfig -h for help on using admconfig.\n"); + System.exit(1); + } + + if (opt.hasOption(_admconfigControlStrings[OPT_USER])) { + String userInfo = opt.getOptionParam( + _admconfigControlStrings[OPT_USER]); + if (null == userInfo) { + System.err.println("ERROR admconfig:"); + System.err.println(" Required parameter for the -user option was not specified."); + showHelp(_admconfigHelpLookup[TC_SHOW_HELP]); + System.exit(1); + } else { + // Use user name if none specified. + int colonIndex = userInfo.indexOf(':'); + + if (-1 == colonIndex) { + _admin = userInfo; + } else if (0 == colonIndex) { + _admin = System.getProperty("user.name"); + } else { + _admin = userInfo.substring(0, colonIndex); + } + + if ((-1 == colonIndex) || + ((colonIndex + 1) == (userInfo.length()))) { + promptForPassword(); + } else { + _password = userInfo.substring((colonIndex + 1)); + } + } + + // Display trace information if in full verbose mode. + if (9 == _verbose) { + System.out.println("admconfig: userid: " + _admin); + System.out.println("admconfig: password: " + + _password); + } + } + if (true == argRequired) { + if ((null == _admin) && (null == _password)) { + promptForAdminInfo(); + + // This case implies that there were no -u option at all. So, need to + // display trace information if in full verbose mode. + if (9 == _verbose) { + System.out.println("admconfig: userid: " + + _admin); + System.out.println("admconfig: password: " + + _password); + } + } else if (null == _admin || _admin.length() == 0) { + _admin = System.getProperty("user.name"); + } else if (null == _password || _password.length() == 0) { + promptForPassword(); + } + } + } + + + + /** + * Handles parsing arguments from an input file, if applicable. + * If the command line has been invoked with the -inputfile option, + * the filename specified as the parameter to the option will be + * opened, read into a string array, and parsed like the arguments + * on the command line. + * + * @param opt the CommandLineParser object for args + * @param args an array of String arguments + */ + protected void handleInputFile(CommandLineParser opt, String args[]) { + + _inputFile = null; + if (opt.hasOption(_admconfigControlStrings[OPT_INPUT_FILE])) { + String inputFile = opt.getOptionParam( + _admconfigControlStrings[OPT_INPUT_FILE]); + if (null == inputFile) { + System.err.println("ERROR admconfig:"); + System.err.println(" No file specified for the -inputFile option. Ignoring option."); + } else { + _inputFile = inputFile; + } + } + + if (_inputFile != null) { + try { + // Read and parse the remaining arguments from the file. + File f = new File(_inputFile); + FileReader fr = new FileReader(f); + long fsize = f.length(); + char[] data = new char[(int) fsize]; + long bytesRead = 0; + while (bytesRead < fsize) { + bytesRead += fr.read(data, (int) bytesRead, + (int)(fsize - bytesRead)); + } + fr.close(); + + String dataString = new String(data); + StringTokenizer tokenizer = new StringTokenizer(dataString); + String token = null; + Vector v = new Vector(); + while (tokenizer.hasMoreTokens()) { + token = tokenizer.nextToken(); + Debug.println( + "TRACE CommandLine.handleInputFile: token from file: " + + token); + v.addElement(token); + } + + int vsize = v.size(); + _fileArgs = new String[vsize]; + v.copyInto(_fileArgs); + _fileOpt = new CommandLineParser( + _admconfigControlStrings, _fileArgs); + + // Parse the arguments from the file. Since the user can + // opt to provide only SOME of the options in the file, + // and the rest in the command line, the required arguments + // do not necessarily have to be found here, as indicated + // by the boolean parameter. If the required arguments are + // not all provided in the file, then they must be provided + // in the command line. See the calling routine. + parseArguments(_fileOpt, _fileArgs, false); + } catch (IOException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" IOException: " + e); + System.err.println(""); + System.exit(1); + } + } + } + + + + /** + * Handles displaying the help information, if applicable. + * If the command line has been invoked with the -help [] + * option, it displays the appropriate help information and + * exits the program. + * + * @param opt the CommandLineParser object + */ + protected void handleHelp(CommandLineParser opt) { + + if (opt.hasOption(_admconfigControlStrings[OPT_HELP])) { + String helpTask = opt.getOptionParam( + _admconfigControlStrings[OPT_HELP]); + if (null == helpTask) { + // Just show main help. + _tc = TC_SHOW_HELP; + } else { + // Show help for specific task. Prepend with the "-" to get the + // desired task code. + _tc = getTaskCode("-" + helpTask, true); + } + showHelp(_admconfigHelpLookup[_tc]); + System.exit(0); + } + } + + + + /** + * Handles displaying the version information, if applicable. + * If the command line has been invoked with the -version option, + * it displays the version information and exits the program. + * + * @param opt the CommandLineParser object + */ + protected void handleVersion(CommandLineParser opt) { + + if (opt.hasOption(_admconfigControlStrings[OPT_VERSION])) { + showVersion(); + System.exit(0); + } + } + + + + /** + * Shows the contents of the help data file that matches the + * lookupString. + * + * @param lookupString the String key used to lookup the help info + */ + protected void showHelp(String lookupString) { + String filename = DATA_FILE; + if (filename != null) { + try { + // Read and parse the remaining arguments from the file. + ClassLoader loader = this.getClass().getClassLoader(); + InputStream is = + loader.getSystemResourceAsStream(PACKAGE_DIR + + "/" + filename); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String line = null; + // Find the lookupString + while ((line = br.readLine()) != null) { + if (line.equalsIgnoreCase(lookupString)) { + break; // Found the string. + } + } + if (line == null) { + System.err.println("ERROR admconfig:"); + System.err.println( + " No help information available for " + + lookupString); + System.err.println(""); + System.exit(1); + } + // Write out everything until either null or '[' is + // is encountered. '[' indicates a different help info. + // Must check for length > 0 because fails on NT. + while ((line = br.readLine()) != null) { + if (line.length() > 0 && line.charAt(0) == '[') { + break; + } + System.out.println(line); + } + br.close(); + } + catch (IOException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" IOException: " + e); + System.err.println(""); + System.exit(1); + } + } + } + + + + /** + * Shows the contents of the version file. + */ + protected void showVersion() { + String filename = VERSION_FILE; + if (filename != null) { + try { + // Read and parse the remaining arguments from the file. + ClassLoader loader = this.getClass().getClassLoader(); + InputStream is = + loader.getSystemResourceAsStream(PACKAGE_DIR + + "/" + filename); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String line = null; + while ((line = br.readLine()) != null) { + System.out.println(line); + } + br.close(); + } catch (IOException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" IOException: " + e); + System.err.println(""); + System.exit(1); + } + } + } + + + + /** + * Prompts for administrator password only. + */ + protected void promptForPassword() { + + // Password is required field. Prompt for it securely, + // i.e. do not echo what user types in! + try { + FileReader fr = new FileReader(FileDescriptor.in); + BufferedReader br = new BufferedReader(fr); + while (true) { + System.out.print("Password: "); + _password = br.readLine(); + if (_password.length() > 0) { + br.close(); + return; // Done. + } + } + } catch (IOException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" IOException: " + e); + System.err.println(""); + System.exit(1); + } + } + + + + /** + * Prompts for the administrator user name and password. + * Side note: tried reusing promptForPassword(), but get + * IOException. + */ + protected void promptForAdminInfo() { + + try { + FileReader fr = new FileReader(FileDescriptor.in); + BufferedReader br = new BufferedReader(fr); + while (true) { + System.out.print("Username: "); + _admin = br.readLine(); + if (_admin.length() > 0) { + break; // Done. + } + } + while (true) { + System.out.print("Password: "); + _password = br.readLine(); + if (_password.length() > 0) { + br.close(); + return; // Done. + } + } + } catch (IOException e) { + System.err.println("ERROR admconfig:"); + System.err.println(" IOException: " + e); + System.err.println(""); + System.exit(1); + } + } + + + /** + * Looks up the task code for the specified task. If the specified + * task does not exist, then the task code for displaying help is + * returned. + * + * @param taskString the task to lookup + * @param alertOnMismatch a boolean flag indicating whether to print error message on mismatches + * @return integer task code matching the specified task, or TC_SHOW_HELP if no match + */ + protected int getTaskCode(String taskString, boolean alertOnMismatch) { + int count = 0; + int taskCode = TC_SHOW_HELP; + String lowerCaseTaskString = taskString.toLowerCase(); + + for (int i = 0; i < _admconfigTaskLookup.length; i++) { + if (_admconfigTaskLookup[i].startsWith(lowerCaseTaskString)) { + count++; + taskCode = i + 1; // Task indices are 1 less + _task = taskString + " (" + _admconfigTaskLookup[i] + ")"; + } + } + + if (count == 0 || count > 1) { + if (alertOnMismatch == true) { + System.err.println("ERROR admconfig:"); + System.err.println(" Unknown or ambiguous task: " + + taskString); + } + return TC_SHOW_HELP; + } + + return taskCode; + } + + + /** + * Gets the name of the specified log file from the Admin Server. It is used + * by the tasks dealing with the error log and access log. It invokes a task + * to retrieve the value of the specified log file in the Admin Server config. + * + * @param log the log file to retrieve + * @return the name of the log file + */ + protected String getLog(String log) { + String encodedResult = null; + try { + // Invoke task to get the log. + URL getLogURL = new URL(_protocol + "://" + _server + "/" + + SERVER_SETUP_TASK + "?op=get&" + + URLByteEncoder.encodeUTF8(log) + "="); + AdmTask getLogTask = new AdmTask(getLogURL, _admin, _password); + // Check for errors. + int execStatus = getLogTask.exec(); + if (execStatus != 0) { + System.err.println("Status = " + execStatus); + System.err.println(" Failed to get " + log); + System.err.println(""); + if (_quitOnError) { + System.exit(execStatus); + } else { + return null; + } + } else { + int taskStatus = getLogTask.getStatus(); + if (taskStatus != 0) { + System.err.println("Status = " + taskStatus); + System.err.println(" Failed to get " + log + + ": " + getLogTask.getResult("NMC_ErrInfo")); + System.err.println(""); + if (_quitOnError) { + System.exit(taskStatus); + } else { + return null; + } + } + } + // Get the log! + String result = (String) getLogTask.getResult(log); + // Make sure it is valid. + if (result.startsWith("admin-serv/") && + result.indexOf("..") == -1) { + encodedResult = URLByteEncoder.encodeUTF8("../../../../" + + result); + } else { + System.err.println("ERROR admconfig:"); + System.err.println(" Cannot run " + _task); + System.err.println(" Invalid log name: " + result); + System.err.println(" Log names must start with \"admin-serv/\" and no \"..\" are allowed.\n"); + if (_quitOnError) { + System.exit(1); + } else { + return null; + } + } + // Success! + } + catch (Exception e) { + System.err.println("ERROR admconfig:"); + System.err.println(" Exception: " + e); + System.err.println(""); + if (_quitOnError) { + System.exit(1); + } else { + return null; // Error + } + } + + // Okay so return result. + return encodedResult; + } +} diff --git a/src/com/netscape/management/admserv/cmdln/CountLogEntriesTask.java b/src/com/netscape/management/admserv/cmdln/CountLogEntriesTask.java new file mode 100644 index 0000000..1dace3d --- /dev/null +++ b/src/com/netscape/management/admserv/cmdln/CountLogEntriesTask.java @@ -0,0 +1,126 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.cmdln; + + +import java.util.Vector; +import java.net.URL; +import com.netscape.management.client.util.AdmTask; +import com.netscape.management.client.util.AdmTaskArg; +import com.netscape.management.client.util.Debug; + + +/** + * Utility class to execute the count log entries task. + * + * @author phlee + * @version %I%, %G% + * @seeAlso AdmTask + */ + +public class CountLogEntriesTask extends AdmTask { + + private int _status; + + + /** + * Constructor to build a task url. + * + * @param url the task url + * @param userID either username or user's DN String + * @param userPassword password of the users The text for the menu label + */ + public CountLogEntriesTask(URL url, String userID, + String userPassword) { + + super(url, userID, userPassword); + _status = 0; // Default to success. + } + + + /** + * Constructor to build a task url. + * + * @param admProtocol protocol used by the target Admin Server (http/https) + * @param admServ host name of the target Admin Server + * @param admPort port number of the target Admin Server + * @param serverID name of the server which task will apply to + * @param taskID task name to be executed + * @param args arguments for the task + * @param userID either username or user's DN String + * @param userPassword password of the user + */ + public CountLogEntriesTask(String admProtocol, String admServ, + int admPort, String serverID, String taskID, Vector args, + String userID, String userPassword) { + + super(admProtocol, admServ, admPort, serverID, taskID, args, + userID, userPassword); + _status = 0; // Default to success. + } + + + /** + * Parsing specific to the count task involving the ReadLog CGI. + * + * @param s the input data line to be parsed + */ + public void parse(String s) { + //Debug.println("TRACE CountLogEntriesTask.parse: " + s); + + int index; + if ((index = s.indexOf(":")) != (-1)) { + // This implies an error occurred. Look at the ReadLog.c CGI. + String name = s.substring(0, index).trim(); + String value = s.substring(index + 1).trim(); + if (name.equalsIgnoreCase("status")) { + _status = Integer.parseInt(value); + } else if (name.equalsIgnoreCase("ErrorString")) { + addResponseArgument(new AdmTaskArg("NMC_ErrInfo", value)); + } else { + addResponseArgument(new AdmTaskArg(name, value)); + } + } else if ((index = s.indexOf("=")) != (-1)) { + // This implies the count was retrieved. Success! + // Look at the ReadLog.c CGI. + String name = s.substring(0, index).trim(); + String value = s.substring(index + 1).trim(); + addResponseArgument(new AdmTaskArg(name, value)); + } else { + super.parse(s); + } + } + + + /** + * Status specific to the count task involving the ReadLog CGI. + * Need to return superclass's getStatus in case exec failed! + * + * @return the integer result of running the task + */ + public int getStatus() { + if (_status != 0) { + return _status; + } else { + return super.getStatus(); + } + } +} diff --git a/src/com/netscape/management/admserv/cmdln/ViewLogEntriesTask.java b/src/com/netscape/management/admserv/cmdln/ViewLogEntriesTask.java new file mode 100644 index 0000000..497dc1b --- /dev/null +++ b/src/com/netscape/management/admserv/cmdln/ViewLogEntriesTask.java @@ -0,0 +1,136 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.cmdln; + + +import java.util.Vector; +import java.net.URL; +import com.netscape.management.client.util.AdmTask; +import com.netscape.management.client.util.AdmTaskArg; +import com.netscape.management.client.util.Debug; + + +/** + * Utility class to execute the view log entries task. + * + * @author phlee + * @version %I%, %G% + * @seeAlso AdmTask + */ + +public class ViewLogEntriesTask extends AdmTask { + + private int _status; + private String _result; + + + /** + * Constructor to build a task url. + * + * @param url the task url + * @param userID either username or user's DN String + * @param userPassword password of the users The text for the menu label + */ + public ViewLogEntriesTask(URL url, String userID, String userPassword) { + + super(url, userID, userPassword); + _status = 0; // Default to success. + _result = ""; + } + + + /** + * Constructor to build a task url. + * + * @param admProtocol protocol used by the target Admin Server (http/https) + * @param admServ host name of the target Admin Server + * @param admPort port number of the target Admin Server + * @param serverID name of the server which task will apply to + * @param taskID task name to be executed + * @param args arguments for the task + * @param userID either username or user's DN String + * @param userPassword password of the user + */ + public ViewLogEntriesTask(String admProtocol, String admServ, + int admPort, String serverID, String taskID, Vector args, + String userID, String userPassword) { + + super(admProtocol, admServ, admPort, serverID, taskID, args, + userID, userPassword); + _status = 0; // Default to success. + _result = ""; + } + + + /** + * Parsing specific to the view task involving the ReadLog CGI. + * + * @param s the input data line to be parsed + */ + public void parse(String s) { + //Debug.println("TRACE ViewLogEntriesTask.parse: " + s); + + int index; + if ((index = s.indexOf(":")) != (-1)) { + // Check for error. Valid result also has colon to delimit time of day. + String name = s.substring(0, index).trim(); + String value = s.substring(index + 1).trim(); + if (name.equalsIgnoreCase("status")) { + _status = Integer.parseInt(value); + } else if (name.equalsIgnoreCase("ErrorString")) { + addResponseArgument(new AdmTaskArg("NMC_ErrInfo", value)); + } else { + _result = _result + "\n" + s; + } + } else { + _result = _result + "\n" + s; + } + } + + + /** + * Status specific to the view task involving the ReadLog CGI. + * Need to return superclass's getStatus in case exec failed! + * + * @return Status of task execution. + */ + public int getStatus() { + if (_status != 0) { + return _status; + } else { + return super.getStatus(); + } + } + + + /** + * Result specific to the view task involving the ReadLog CGI. + * + * @return Result of task. + */ + public Object getResult(String name) { + if (name.equalsIgnoreCase("Result")) { + return _result; + } else { + return null; + } + } +} diff --git a/src/com/netscape/management/admserv/cmdln/admconfig.dat b/src/com/netscape/management/admserv/cmdln/admconfig.dat new file mode 100644 index 0000000..c1d564c --- /dev/null +++ b/src/com/netscape/management/admserv/cmdln/admconfig.dat @@ -0,0 +1,668 @@ +[help-main] + +NAME: + + admconfig - command line tool for Administration Server + + +SYNOPSIS: + + admconfig [options] [args] [ [args] ...] + + +OPTIONS: + + Valid [options] are: + + -con[tinueOnError] + Finish the remaining tasks even when an error occurs. Default + behavior is to quit when any task fails without running the + remaining tasks. + + -enc[ryption] + Use encrypted protocol (https) to connect to the server. The + default protocol is http. + + -h[elp] [] + Display the usage information [for task]. To display the usage + information for a particular task, specify the task as the + argument to -h without the leading hyphen, i.e. -h restart. + + -i[nputFile] + Get options from the specified file. The same options can + also be specified on the command line along with the option + file. In this case, the options on the command line override + the options in the file. The -inputFile option within the + option file is ignored to prevent recursion. + + -ser[ver] []: + Connect to the server on host at specified port. If no host is + specified, the localhost is used. The server port number + (preceded by the colon) is required. + + -u[ser] []:[] + Connect to the server using username and password. If the + username is not specified, the user's login name is used. If + the password is not specified, the user is prompted for the + password. The password is echoed back on the user's screen so + if security is a concern, the -inputFile option should be used + to provide the username and password in a file with suitable + permissions. Note that if the -user option is specified, then + at the minimum, the colon must be specified. If the -user + option is not specified, then the user is prompted for both + the username and password. + + -verb[ose] [<0-9>] + Set the level of screen output (9=full output, 0=no output). + The default level is 5. + + -vers[ion] + Display the version and copyright information. + + The [options] can be specified using the terse single character form + such as -u if applicable, or they can be specified using the longer but + more descriptive form such as -user. The complete option name does not + have to be specified. For example, -us will work just as well as -user. + The option name just needs to be specified so that it is not ambiguous + among other [options] as well as the tasks below. + + Note that [options] are not case sensitive. Thus, -USER and -User are + both accepted as the -user option. + + + Valid includes: + + -countA[ccessLogEntries] + Count the number of entries in the access log file. + -viewA[ccessLogEntries] + View the specified entries in the access log file. + + -countE[rrorLogEntries] + Count the number of entries in the error log file. + -viewE[rrorLogEntries] + View the specified entries in the error log file. + + -enableD[SGWAccess] + Enable Directory Server Gateway access to the admin server. + -disableD[SGWAccess] + Disable Directory Server Gateway access to the admin server. + + -enableE[ndUserAccess] + Enable end user access to the admin server. + -disableE[ndUserAccess] + Disable end user access to the admin server. + + -getAc[cessLog] + Get the name of the server access log file. + -setAc[cessLog] + Set the name of the server access log file. + + -getAdd[resses] + Get the addresses from which connections are allowed. + -setAdd[resses] + Set the addresses from which connections are allowed. + + -getAdminUI[D] + Get the admistrator's username. + -setAdminUI[D] + Set the admistrator's username to the specified UID. + -setAdminP[wd] + Set the admistrator's password to the specified value. + + -getAdminUs[ers] + Get the name of the adminusers file. + -setAdminUs[ers] + Set the name of the adminusers file. + + -getCa[cheLifetime] + Get the amount of time that the user authentication is cached. + -setCa[cheLifetime] + Set the amount of time to cache the user authentication. + + -getCl[assname] + Get the Java classname for the admin server. + -setCl[assname] + Set the Java classname for the admin server. + + -getDe[faultAcceptLanguage] + Get the defaultacceptlanguage. + -setDe[faultAcceptLanguage] + Set the defaultacceptlanguage. + + -getDS[Config] + Retrieve the current LDAP server host, port, baseDN, and whether + the LDAP server is running SSL. + -setDS[Config] + Set the LDAP server host, port, baseDN, and whether the LDAP + server is running SSL. + + -getE[rrorLog] + Get the name of the server error log file. + -setE[rrorLog] + Set the name of the server error log file. + + -getH[osts] + Get the hosts from which connections are allowed. + -setH[osts] + Set the hosts from which connections are allowed. + + -getO[neACLDir] + Get the oneacldir. + -setO[neACLDir] + Set the oneacldir. + + -getPo[rt] + Get the current admin server port number. + -setPo[rt] + Set the admin server port number. + + -getSe[rverAddress] + Get the current admin server address. + -setSe[rverAddress] + Set the admin server address. + + -getSy[ystemUser] + Get the user name that the server is currently running as. + -setSy[ystemUser] + Set the user name that the server should run as. + + -getU[GDSConfig] + Retrieve the current user/group LDAP server information, + including the host, port, baseDN, and authentication DN. + -setU[GDSConfig] + Set the user/group LDAP server host, port, baseDN, + authentication DN, and authentication password. + + -r[estart] + Restart the admin server. + + -st[op] + Stop the admin server. + + The task to be done can be specified using the abbreviated name such as + -r for restarting the server or using the complete name -restart. + The task name just needs to be specified so that it is not ambiguous + among other tasks or the [options] above. The task key words are also + case insensitive, so both -RESTART and -Restart are accepted as the + -restart task. + + Multiple tasks can be run from the same invocation of admconfig. Tasks + specified in an input file are run first. Tasks are run in the order + specified in the input file and command line. + + +EXAMPLES: + + The following example changes the port number to 33333 and restarts the + admin server. Note that the verbose level will be set to 5. + + % admconfig -server jaffer.mcom.com:22222 -user phlee:password + -verbose 5 -setPort 33333 -restart + + + The following example retrieves the hosts from which connections are + allowed. Note that the verbose level will be set to 9. + + % admconfig -ser jaffer.mcom.com:33333 -u phlee:password -verb -geth + + + The following example displays the help information for restarting the + admin server. + + % admconfig -h r + + +[help-getaccesslog] + +usage: admconfig [options] -getAc[cessLog] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getaddresses] + +usage: admconfig [options] -getAdd[resses] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getclassname] + +usage: admconfig [options] -getCl[assname] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getcachelifetime] + +usage: admconfig [options] -getCa[cheLifetime] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getadminusers] + +usage: admconfig [options] -getAdminUs[ers] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getdefaultacceptlanguage] + +usage: admconfig [options] -getDe[faultAcceptLanguage] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-geterrorlog] + +usage: admconfig [options] -getE[rrorLog] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-gethosts] + +usage: admconfig [options] -getH[osts] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getoneacldir] + +usage: admconfig [options] -getO[neACLDir] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getport] + +usage: admconfig [options] -getPo[rt] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getserveraddress] + +usage: admconfig [options] -getSe[rverAddress] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getsystemuser] + +usage: admconfig [options] -getSy[ystemUser] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-restart] + +usage: admconfig [options] -r[estart] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-setaccesslog] + +usage: admconfig [options] -setAc[cessLog] + + Required parameter includes: + New server access log file. + + Use the admconfig -h option for help on [options]. + + +[help-setaddresses] + +usage: admconfig [options] -setAdd[resses] + + Required parameter includes: + New addresses from which connections are allowed. + + Use the admconfig -h option for help on [options]. + + +[help-setclassname] + +usage: admconfig [options] -setCl[assname] + + Required parameter includes: + New admin class file name. + + Use the admconfig -h option for help on [options]. + + +[help-setcachelifetime] + +usage: admconfig [options] -setCa[cheLifetime] + + Required parameter includes: + New cache lifetime in msecs. + + Use the admconfig -h option for help on [options]. + + +[help-setadminusers] + +usage: admconfig [options] -setAdminUs[ers] + + Required parameter includes: + New name for the admin users file. + + Use the admconfig -h option for help on [options]. + + +[help-setdefaultacceptlanguage] + +usage: admconfig [options] -setDe[faultAcceptLanguage] + + Required parameter includes: + New default accept language. + + Use the admconfig -h option for help on [options]. + + +[help-seterrorlog] + +usage: admconfig [options] -setE[rrorLog] + + Required parameter includes: + New server error log file. + + Use the admconfig -h option for help on [options]. + + +[help-sethosts] + +usage: admconfig [options] -setH[osts] + + Required parameter includes: + New hosts from which connections are allowed. + + Use the admconfig -h option for help on [options]. + + +[help-setoneacldir] + +usage: admconfig [options] -setO[neACLDir] + + Required parameter includes: + New ACL directory. + + Use the admconfig -h option for help on [options]. + + +[help-setport] + +usage: admconfig [options] -setPo[rt] + + Required parameter includes: + New server port number. + + Use the admconfig -h option for help on [options]. + + +[help-setserveraddress] + +usage: admconfig [options] -setSe[rverAddress]

+ + Required parameter includes: +
New server address. + + Use the admconfig -h option for help on [options]. + + +[help-setsystemuser] + +usage: admconfig [options] -setSy[stemUser] + + Required parameter includes: + New user name that the server should run as. + + Use the admconfig -h option for help on [options]. + + +[help-stop] + +usage: admconfig [options] -st[op] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-counterrorlogentries] + +usage: admconfig [options] -countE[rrorlogEntries] + + This task should be performed prior to -viewErrorLogEntries in order + to determine the number of entries that can be viewed in the error log. + + There are no additional options or parameters for this task. + + Use the admconfig -h option for help on [options]. + + +[help-viewerrorlogentries] + +usage: admconfig [options] -viewE[rrorLogEntries] \" \" + + Required parameter includes: + The first log entry number to start displaying from. + The last log entry number to display. + + The backslash character is required before the quotes surrounding the two + arguments to -viewErrorLogEntries. If not provided, on UNIX systems, the + shell will evaluate the quotes and pass the arguments without the quotes + to the command line. This will result in only being assigned as + the parameter to -viewErrorLogEntries. The backslash character before the + quotes will prevent the quotes from being evaluated and allow both arguments + to be assigned as the parameter to -viewErrorLogEntries. + + Use the admconfig -h option for help on [options]. + + +[help-countaccesslogentries] + +usage: admconfig [options] -countA[ccesslogEntries] + + This task should be performed prior to -viewAccessLogEntries in order + to determine the number of entries that can be viewed in the access log. + + There are no additional options or parameters for this task. + + Use the admconfig -h option for help on [options]. + + +[help-viewaccesslogentries] + +usage: admconfig [options] -viewA[ccessLogEntries] \" \" + + Required parameter includes: + The first log entry number to start displaying from. + The last log entry number to display. + + The backslash character is required before the quotes surrounding the two + arguments to -viewAccessLogEntries. If not provided, on UNIX systems, the + shell will evaluate the quotes and pass the arguments without the quotes + to the command line. This will result in only being assigned as + the parameter to -viewAccessLogEntries. The backslash character before the + quotes will prevent the quotes from being evaluated and allow both arguments + to be assigned as the parameter to -viewAccessLogEntries. + + Use the admconfig -h option for help on [options]. + + +[help-enableenduseraccess] + +usage: admconfig [options] -enableE[ndUserAccess] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-disableenduseraccess] + +usage: admconfig [options] -disableE[ndUserAccess] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-enabledsgwaccess] + +usage: admconfig [options] -enableD[SGWAccess] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-disabledsgwaccess] + +usage: admconfig [options] -disableD[SGWAccess] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-getadminuid] + +usage: admconfig [options] -getAdminUI[D] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-setadminuid] + +usage: admconfig [options] -setAdminUI[D] + + Required parameter includes: + The new user ID for the administrator. + + Use the admconfig -h option for help on [options]. + + +[help-setadminpwd] + +usage: admconfig [options] -setAdminP[WD] + + Required parameter includes: + The new password for the administrator. + + Use the admconfig -h option for help on [options]. + + +[help-getdsconfig] + +usage: admconfig [options] -getDS[Config] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-setdsconfig] + +usage: admconfig [options] -setDS[Config] \" \" + + Required parameter includes: + The LDAP Server host name. + The LDAP Server port number. + "true" | "false" depending on whether to use the Secure + Sockets Layer to communicate with the LDAP Server. + + The backslash character is required before the quotes surrounding the four + arguments to -setDSConfig. If not provided, on UNIX systems, the shell will + evaluate the quotes and pass the arguments without the quotes to the + command line. This will result in only being assigned as the + parameter to -setDSConfig. The backslash character before the quotes will + prevent the quotes from being evaluated and allow all arguments to be + assigned as the parameter to -setDSConfig. + + IMPORTANT NOTE: The space character is used to parse these four arguments. + Therefore, none of the arguments may have spaces in them. In order to support + spaces for the argument, the parsing function for this argument uses + a character replacement scheme to allow spaces to be specified. Simply, + whenever a space is required, the '+' character should be used to indicate to + the parser to convert the character to space. For example, in order to specify + "o=Netscape Communications Corp" as the , uses must type instead + "o=Netscape+Communications+Corp". Because the '+' character is used in place + of the space character, the '+' character cannot be used as an actual value. For + example, there is currently no way to specify "o=A+B Industries". + + Use the admconfig -h option for help on [options]. + + +[help-getugdsconfig] + +usage: admconfig [options] -getU[GDSConfig] + + There are no additional options or parameters for this task. + Use the admconfig -h option for help on [options]. + + +[help-setugdsconfig] + +usage: admconfig [options] -setU[GDSConfig] [\" \"] + + Optional arguments includes: + The user/group LDAP Server host name. + The user/group LDAP Server port number. + The user/group LDAP Server base DN. + "true" | "false" depending on whether to use the Secure + Sockets Layer to communicate with the LDAP Server. + Authentication DN used to bind to LDAP Server. + Authentication password used to bind to LDAP Server. + + -setUGDSConfig can be invoked in two ways, with or without parameters. If + this task is invoked without any arguments, for example, + + % admconfig -server jaffer.mcom.com:22222 -user admin:password -setUGDSConfig + + then the directory server configuration is reset to the installation + defaults. On the other hand, if the task is invoked with all six arguments + (all six arguments are required), then they override the installation + defaults or the previous values that may have been set. + + The backslash character is required before the quotes surrounding the six + arguments to -setUGDSConfig. If not used, on UNIX systems, the shell will + evaluate the quotes and pass the arguments without the quotes to admconfig. + This will result in only being assigned as the parameter to + -setUGDSConfig, which will cause the task to fail due to missing arguments. + The backslash character before the quotes will prevent the quotes from being + evaluated and allow all arguments to be assigned as the parameter to + -setUGDSConfig. + + The , , , and arguments are used to create the + LDAP URL for the ugdsconfig.dirurl attribute. The argument is used to + set the ugdsconfig.binddn attribute, and the argument is used to set + the ugdsconfig.bindpw attribute. + + IMPORTANT NOTE: The space character is used to parse these six arguments. + Therefore, none of the arguments may have spaces in them. In order to support + spaces for arguments such as , , and , the parsing function + for these three arguments uses a character replacement scheme to allow spaces + to be specified. Simply, whenever a space is required, the '+' character + should be used to indicate to the parser to convert the character to space. + For example, in order to specify "cn=directory manager" as the , users + must type "cn=directory+manager". Because the '+' character is used in place + of the space character, the '+' character cannot be used as an actual value. + For example, there is currently no way to specify "[r@K+h1s" as the + since this will be translated to "Cr@K h1s". + + Use the admconfig -h option for help on [options]. + + diff --git a/src/com/netscape/management/admserv/cmdln/sample-nt-options b/src/com/netscape/management/admserv/cmdln/sample-nt-options new file mode 100644 index 0000000..71b502f --- /dev/null +++ b/src/com/netscape/management/admserv/cmdln/sample-nt-options @@ -0,0 +1,3 @@ +-s phlee.mcom.com:31044 +-u admin:admin +-q 0 diff --git a/src/com/netscape/management/admserv/cmdln/sample-unix-options b/src/com/netscape/management/admserv/cmdln/sample-unix-options new file mode 100644 index 0000000..76f2d32 --- /dev/null +++ b/src/com/netscape/management/admserv/cmdln/sample-unix-options @@ -0,0 +1,3 @@ +-s jaffer.mcom.com:31044 +-u admin:admin +-q 0 diff --git a/src/com/netscape/management/admserv/cmdln/version.dat b/src/com/netscape/management/admserv/cmdln/version.dat new file mode 100644 index 0000000..55a06f0 --- /dev/null +++ b/src/com/netscape/management/admserv/cmdln/version.dat @@ -0,0 +1,5 @@ + +Administration Server Command Line (admconfig) version 7.2.1 + +Copyright (C) 2005 Red Hat, Inc. +All rights reserved. diff --git a/src/com/netscape/management/admserv/config/ActionMonitorPanel.java b/src/com/netscape/management/admserv/config/ActionMonitorPanel.java new file mode 100644 index 0000000..e93c20e --- /dev/null +++ b/src/com/netscape/management/admserv/config/ActionMonitorPanel.java @@ -0,0 +1,219 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.util.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.border.EmptyBorder; +import com.netscape.management.client.*; +import com.netscape.management.client.util.*; +import com.netscape.management.nmclf.*; + +import java.awt.*; +import java.awt.event.*; + +public class ActionMonitorPanel extends JPanel { + + static ResourceSet _resource; + static String _i18nActionAborted, _i18nTooltipInterrupt; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.config.config"); + _i18nActionAborted = _resource.getString("actionmon", "ActionAborted"); + _i18nTooltipInterrupt = _resource.getString("actionmon", "TooltipInterrupt"); + } + + ThreadGroup _actionTG; + JPanel _mainPanel; + JLabel _lblStatus; + JTextArea _txtStatus; + ButtonBar _buttonBar; + JButton _btnStop; + ActionListener _stopListener = null; + private static ActionMonitorPanel _activeInstance; + boolean _multilinedStatus; + + public ActionMonitorPanel() { + this(false); + } + + public ActionMonitorPanel(boolean multilinedStatus) { + + //Dimension d = new Dimension(350,250); + setLayout(new BorderLayout(12, 12)); + // setMinimumSize(d); + //setPreferredSize(d); + _multilinedStatus = multilinedStatus; + createUILayout(); + } + + public static ActionMonitorPanel getActiveInstance() { + return _activeInstance; + } + + public boolean isMultilined() { + return _multilinedStatus; + } + + private void createUILayout() { + createButtonBar(); + createMainPanel(); + add(_mainPanel, BorderLayout.CENTER); + add(_buttonBar, BorderLayout.SOUTH); + } + + public void createMainPanel() { + _mainPanel = new JPanel(new BorderLayout()); + if (_multilinedStatus) { + _txtStatus = new JTextArea(15, 40); + _txtStatus.setBackground( + UIManager.getColor("Button.background")); //_btnStop.getBackground()); + _txtStatus.setEditable(false); + _mainPanel.add(new JScrollPane(_txtStatus)); + Dimension d = new Dimension(550, 250); + setMinimumSize(d); + setPreferredSize(d); + + } else { + _mainPanel.add(_lblStatus = new JLabel(" ", JLabel.CENTER)); + Dimension d = new Dimension(350, 250); + setMinimumSize(d); + setPreferredSize(d); + } + } + + private void createButtonBar() { + _buttonBar = new ButtonBar(new String[]{ButtonBar.cmdCancel}, + new String[]{ButtonBar._i18nCancelButton} , true); + _btnStop = _buttonBar.getButton(ButtonBar.cmdCancel); + _btnStop.setToolTipText(_i18nTooltipInterrupt); + _buttonBar.addActionListener(_stopAction); + } + + + ActionListener _stopAction = new ActionListener() { + public void actionPerformed(ActionEvent e) { + ActionMonitorPanel.this.monitorProgressStop( + _i18nActionAborted); + if (_stopListener != null) { + _stopListener.actionPerformed(e); + } + } + }; + + public void monitorProgressStart(String msg, ThreadGroup tg, + ActionListener stopListener) { + if (_activeInstance != null) + _activeInstance.monitorProgressStop(""); + _actionTG = tg; + _stopListener = stopListener; + _btnStop.setEnabled(true); + setActionBusyCursor(true, msg, _mainPanel); + setStatusText(msg); + _activeInstance = this; + //Debug.println("Start Monitor"); + } + + + public void setInterruptEnabled(boolean flag) { + _btnStop.setEnabled(flag); + } + + public synchronized void monitorProgressStop(String msg) { + //Debug.println("Stop Monitor"); + if (_actionTG != null && + Thread.currentThread().getThreadGroup() != _actionTG) { + // need to terminate _actionTG + terminateActionThreadGroup(); + } + + setStatusText(msg); + _btnStop.setEnabled(false); + setActionBusyCursor(false, msg, _mainPanel); + _actionTG = null; + _activeInstance = null; + } + + public synchronized void monitorProgressWaitForClose() { + _btnStop.setLabel(ButtonBar._i18nCloseButton); + JButtonFactory.initializeMnemonic(_btnStop); + _btnStop.repaint(); + _btnStop.setToolTipText(null); + setActionBusyCursor(false, "", _mainPanel); + _activeInstance = null; + } + + public void setStatusText(String text) { + if (_multilinedStatus) { + _txtStatus.append("\n"); + _txtStatus.append(text); + } else { + _lblStatus.setText(text); + } + } + + public void setStatusTextSameLIne(String text) { + if (_multilinedStatus) { + _txtStatus.append(text); + } else { + _lblStatus.setText(text); + } + } + + + private void terminateActionThreadGroup() { + Debug.println("Therminate Action Thread Group " + + _actionTG.activeCount()); + + // First interrrupt all active threads + /*Thread[] threads = new Thread[_actionTG.activeCount()]; + _actionTG.enumerate(threads); + for (int i=0; i < threads.length; i++) { + Debug.println("Interrupting " + threads[i].getName()); + threads[i].interrupt(); + }*/ + // Then stop them all after a 0.5 sec delay. The delay is meant to give the + // interrupted threads a chance to run and do some cleanup + try { + Thread.currentThread().sleep(500); + } catch (Exception e) {} + _actionTG.stop(); + } + + public void setActionBusyCursor(boolean busy, String text, + Component c) { + Cursor cursor = null; + if (busy) { + BaseConfigPanel.setProgressIndicator(this, text, -1, 0); + cursor = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR); + } else { + BaseConfigPanel.clearProgressIndicator(this); + cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); + } + if (_txtStatus != null) + _txtStatus.setCursor(cursor); + if (_lblStatus != null) + _lblStatus.setCursor(cursor); + if (_btnStop.getParent() != null) + _btnStop.getParent().setCursor(cursor); + } +} diff --git a/src/com/netscape/management/admserv/config/BaseConfigPanel.java b/src/com/netscape/management/admserv/config/BaseConfigPanel.java new file mode 100644 index 0000000..8c89d5e --- /dev/null +++ b/src/com/netscape/management/admserv/config/BaseConfigPanel.java @@ -0,0 +1,643 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.lang.reflect.Method; + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.border.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.*; +import com.netscape.management.nmclf.*; +import com.netscape.management.admserv.panel.DialogFrame; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ + +/** + * Base Config Panel provides a framework for configing panels. It hosts a plugin config + * panel IPluginConfigPanel and a common command button bar. The changes inside the + * plugin config panel are monitored using the edit monitor. +*/ +public class BaseConfigPanel extends JPanel implements SuiConstants { + + static ResourceSet _resource; + static String _i18nStatusLoading, _i18nStatusSaving, _i18nLoadFailed; + static String _i18nSaveToolTip, _i18nResetToolTip, _i18nHelpToolTip; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.config.config"); + _i18nStatusLoading = _resource.getString("baseconfig", "StatusLoading"); + _i18nStatusSaving = _resource.getString("baseconfig", "StatusSaving"); + _i18nLoadFailed = _resource.getString("baseconfig", "LoadFailed"); + _i18nSaveToolTip = _resource.getString("baseconfig", "SaveToolTip"); + _i18nResetToolTip = _resource.getString("baseconfig", "ResetToolTip"); + _i18nHelpToolTip = _resource.getString("baseconfig", "HelpToolTip"); + } + + static private String[] _toolTips = { _i18nSaveToolTip, + _i18nResetToolTip, + null, + _i18nHelpToolTip}; + + protected JLabel _heading; + protected ButtonBar _cmdButtons; + protected JComboBox _targetChoice; + protected EditMonitor _editMonitor; + protected JPanel _editPanel; + protected ActionMonitorPanel _actionPanel = new ActionMonitorPanel(); + protected CardLayout _card; + protected boolean _initialized, _dataValid, _dataSaved; + + static protected Font _fontHeadingLabel = UIManager.getFont("Title.font"); + static protected Font _fontLabel = UIManager.getFont("Panel.font"); + + protected IPluginConfigPanel _pluginPanel; + protected boolean _hasTitle; + protected boolean _inDialog; + + /** + * Constructor + * + * @param pluginPanel A plugin panel + */ + public BaseConfigPanel(IPluginConfigPanel pluginPanel) { + this(pluginPanel, false); + } + + /** + * Constructor + * + * @param pluginPanel A plugin panel + * @param inDialog A flag whether the base config panel will reside in a dialog + */ + public BaseConfigPanel(IPluginConfigPanel pluginPanel, + boolean inDialog) { + int vi = VERT_WINDOW_INSET - COMPONENT_SPACE; + int hi = HORIZ_WINDOW_INSET - COMPONENT_SPACE; + setLayout(_card = new CardLayout()); + if (!inDialog) + setBorder(BorderFactory.createEmptyBorder(vi, hi, vi, hi)); + + _inDialog = inDialog; + + //_actionPanel = new ActionMonitorPanel(); + //add(_actionPanel, "action"); + + _editPanel = new JPanel(); + _editPanel.setLayout( new BorderLayout(/*hgap=*/0, + /*vgap=*/SuiLookAndFeel.SEPARATED_COMPONENT_SPACE)); + add(_editPanel, "edit"); + + setPluginPanel(pluginPanel); + } + + /** + * Set the plugin planel + * @param pluginPanel A plugin panel + */ + public void setPluginPanel(IPluginConfigPanel pluginPanel) { + _pluginPanel = pluginPanel; + _cmdButtons = createCommandButtonBar(); + _editMonitor = createEditMonitor(); + + _hasTitle = (_pluginPanel.getTitleText() != null && + _pluginPanel.getTitleText().length() != 0); + _heading = createHeadingLabel(_pluginPanel.getTitleText()); + + createEditLayout(); + + if (isPluginModelLoaded()) { + showPanel(_editPanel); //_card.show(this, "edit"); + initPluginPanel(); + } else { + monitorPluginPanelInit(); + } + } + + + public boolean isInitialized() { + if (_initialized) + showPanel(_editPanel); + return _initialized; + } + + /** + * Return the plugin panel + * @returns The plugin panel + */ + public IPluginConfigPanel getPluginPanel() { + return _pluginPanel; + } + + + /** + * Return the base config panel for the contained component + * @returns BaseConfigPanel instance or null + */ + static public BaseConfigPanel getInstance(Component c) { + while (c != null && ! (c instanceof BaseConfigPanel)) { + c = c.getParent(); + } + return (BaseConfigPanel) c; + } + + + + // Check if plugin panel data model is loaded + protected boolean isPluginModelLoaded() { + IConfigDataModel data = _pluginPanel.getDataModel(); + return (data != null && data.isLoaded()); + } + + /** + * Initialize the plugin panel. The method will block the current thread if + * data.load() is called. + * @see monitorPluginPanelInit() + */ + protected void initPluginPanel() { + _initialized = false; + try { + IConfigDataModel data = _pluginPanel.getDataModel(); + if (data != null && !data.isLoaded()) { + data.load(); + } + _pluginPanel.initialize(); + } catch (ConfigPanelException e) { + ConfigErrorDialog.showDialog(_pluginPanel.getPanel(), e); + return; + } + + _pluginPanel.registerEditComponents(_editMonitor); + _editMonitor.start(); + _initialized = true; + } + + /** + * This method is used as a wrapper for initPluginPanel() if plugin data model is + * not loaded. It runs in a separate thread so that AWR Event Queue thread does not + * get locked dupring the remote operation. The method is interacting with the + * action panel to show the status and to enable the user to interrupt the action. + */ + protected void monitorPluginPanelInit() { + + /* DT 1/6/98 granting UniversalThreadGroupAccess before creating thread groups */ + Method m = Permissions.getEnablePrivilegeMethod(); + + if (m != null) { + Object[] args = new Object[1]; + args[0] = "UniversalThreadGroupAccess"; + + try { + m.invoke(null, args); + } catch (Exception e) { + Debug.println( + "ThreadGroup:monitorPluginPanelInit():unable to grant ThreadGroup privileges:" + e); + } + } + + showPanel(_actionPanel); //_card.show(this, "action"); + + final ThreadGroup tg = new ThreadGroup("LongActionTG"); + Thread t = new Thread(tg, "LongAction") { + public void run() { + // Give GUI time to complete setup + try { + Thread.currentThread().sleep(200); + } catch (Exception e) {} + _actionPanel.monitorProgressStart( + _i18nStatusLoading, tg, _stopAction); + BaseConfigPanel.this.initPluginPanel(); + + _actionPanel.monitorProgressStop(_initialized ? + "" : _i18nLoadFailed); + + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + if (_initialized) { + showPanel(_editPanel); + //_card.show(BaseConfigPanel.this, "edit"); + } else if ( + _inDialog) { + closeDialog(); + } + } + } + ); + } catch (Exception e1) { + Debug.println( + "monitorPluginPanelInit invokeAndWait " + + e1); + } + + } + + ActionListener _stopAction = new ActionListener() { + public void actionPerformed( + ActionEvent e) { + closeDialog(); + } + }; + + }; + t.start(); + } + + + /** + * Panel layout + */ + protected void createEditLayout() { + if (_heading != null) { + _editPanel.add(createNorthPanel(), BorderLayout.NORTH); + } + + if (_pluginPanel != null) { + _editPanel.add(createCenterPanel(), BorderLayout.CENTER); + } + + if (_cmdButtons != null) { + _editPanel.add(createSouthPanel(), BorderLayout.SOUTH); + } + } + + // North panel in border layout hosts heading + protected JPanel createNorthPanel() { + JPanel p = new JPanel( new BorderLayout(/*hgap=*/0, + /*vgap=*/SuiLookAndFeel.SEPARATED_COMPONENT_SPACE)); + + if (_heading != null) { + p.add(_heading, BorderLayout.NORTH); + } + return p; + } + + // Center panel is border layout is hosting the plugin panel + protected JPanel createCenterPanel() { + JPanel p = new JPanel(new BorderLayout()); + p.add(_pluginPanel.getPanel(), BorderLayout.CENTER); + return p; + } + + // Heading label + protected JLabel createHeadingLabel(String label) { + + if (label == null || label.length() == 0) { + return null; + } + JLabel heading = new JLabel(label, SwingConstants.LEFT); + heading.setFont(_fontHeadingLabel); + return heading; + } + + // South panel in border layout is hosting command button bar + protected JPanel createSouthPanel() { + JPanel p = new JPanel(new BorderLayout()); + p.add(_cmdButtons, BorderLayout.EAST); + return p; + } + + + /** + * Command Button Bar + */ + public ButtonBar createCommandButtonBar() { + ButtonBar bb = new ButtonBar(_inDialog, _toolTips); + bb.addActionListener(_btnListener); + return bb; + } + + + public ButtonBar getCommandButtonBar() { + return _cmdButtons; + } + + + /** + * Edit Monitor + */ + protected EditMonitor createEditMonitor() { + if (_cmdButtons == null) + return null; + EditMonitor monitor = new EditMonitor(); + monitor.addEnableComponent(_cmdButtons.getButton(ButtonBar.cmdOK)); + + // When in dialog, sematic for Cancel button is Close the dialog. + // When in RHP, sematic for Cancel button is Reset the panel content + if (!_inDialog) { + monitor.addEnableComponent( + _cmdButtons.getButton(ButtonBar.cmdCancel)); + } + + return monitor; + } + + public EditMonitor getEditMonitor() { + return _editMonitor; + } + + /** + * Listener for events from the button bar + */ + ActionListener _btnListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + commandButtonAction(e.getActionCommand()); + } + }; + + + /** + * Handling of command buttons actions + */ + protected void commandButtonAction(String command) { + if (command.equals(ButtonBar.cmdOK)) { + _dataValid = _dataSaved = false; + try { + _pluginPanel.applyChanges(); + _dataValid = true; + if (isPluginModelModified()) { + //monitorPluginPanelSave(); + monitorLongAction(_i18nStatusSaving, new Runnable() { + public void run () { + BaseConfigPanel.this.savePluginPanel(); + } + } + ); + } else { + _editMonitor.setDirtyFlag(false); + } + } catch (ConfigPanelException e) { + ConfigErrorDialog.showDialog(_pluginPanel.getPanel(), e); + } + + } else if (command.equals(ButtonBar.cmdCancel)) { + if (_inDialog) { + closeDialog(); + return; + } + try { + _pluginPanel.resetContent(); + } catch (ConfigPanelException e) { + ConfigErrorDialog.showDialog(_pluginPanel.getPanel(), e); + return; + } + + _editMonitor.setDirtyFlag(false); + } + /*else if (command.equals(ButtonBar.cmdClose)) { + closeDialog(); + }*/ + else if (command.equals(ButtonBar.cmdHelp)) { + _pluginPanel.showHelp(); + } + else { + Debug.println(command + " not implemented"); + } + } + + // Check if model is modified + protected boolean isPluginModelModified() { + IConfigDataModel data = _pluginPanel.getDataModel(); + return (data != null && data.isModified()); + } + + + /** + * Save the plugin panel data model, i.e. copy the data to the server. + * The method will block the current thread + */ + void savePluginPanel() { + try { + _pluginPanel.getDataModel().save(); + _dataSaved = true; + _pluginPanel.resetContent(); + _editMonitor.setDirtyFlag(false); + closeDialog(); + } catch (ConfigPanelException e) { + ConfigErrorDialog.showDialog(_pluginPanel.getPanel(), e); + } + } + + /** + * This method is used to execute long actions. It runs in a separate + * thread so that AWR Event Queue thread does not get locked during the remote + * operation. The method is interacting with the action panel to show the status + * and to enable the user to interrupt the action. + */ + public void monitorLongAction(Runnable action) { + monitorLongAction(_i18nStatusLoading, action); + } + + public void monitorLongAction(String msg, Runnable action) { + + /* DT 1/6/98 granting UniversalThreadGroupAccess before creating thread groups */ + Method m = Permissions.getEnablePrivilegeMethod(); + + if (m != null) { + Object[] args = new Object[1]; + args[0] = "UniversalThreadGroupAccess"; + + try { + m.invoke(null, args); + } catch (Exception e) { + Debug.println( + "BaseConfigPanel:monitorLongAction():unable to grant ThreadGroup privileges:" + e); + } + } + + showPanel(_actionPanel); //_card.show(this, "action"); + + final ThreadGroup tg = new ThreadGroup("LongActionTG"); + final Runnable actionTask = action; + final String actionMsg = msg; + Thread t = new Thread(tg, "LongAction") { + public void run() { + _actionPanel.monitorProgressStart(actionMsg, + tg, _stopAction); + actionTask.run(); + _actionPanel.monitorProgressStop(""); + SwingUtilities.invokeLater( new Runnable() { + public void run() { + showPanel(_editPanel); //_card.show(BaseConfigPanel.this, "edit"); + } + }); + } + + ActionListener _stopAction = new ActionListener() { + public void actionPerformed( + ActionEvent e) { + showPanel(_editPanel); //_card.show(BaseConfigPanel.this, "edit"); + } + }; + + }; + + t.start(); + } + + + /** + * Check if running inside a dialog. + */ + protected Window getDialog() { + Component c = this; + while ((c = c.getParent()) != null) { + if (c instanceof Dialog || c instanceof JDialog) { + return (Window) c; + } + } + return null; + } + + + /** + * Close dialog if base config panel is running inside a dialog + */ + protected void closeDialog() { + Window dialog = getDialog(); + if (dialog != null) { + dialog.setVisible(false); + //dialog.dispose(); + //ModalDialogUtil.sleep(); + } + } + + /** + * Consistent UI methods + */ + public static Border createGroupBorder(String label) { + TitledBorder titleBorder = BorderFactory.createTitledBorder( + BorderFactory.createEtchedBorder(), label); + Border interiorBorder = + BorderFactory.createEmptyBorder(COMPONENT_SPACE, + COMPONENT_SPACE, COMPONENT_SPACE, COMPONENT_SPACE); + return BorderFactory.createCompoundBorder(titleBorder, + interiorBorder); + } + + public static Font getLabelFont() { + return _fontLabel; + } + + public static Font getHeadingLabelFont() { + return _fontHeadingLabel; + } + + + // A workaround for a repaint problem which started with Swing 0.7. The problem + // is related to using CardLayout + private JPanel _currentPanel; + protected void showPanel(JPanel panel) { + if (panel == _actionPanel) { + add(_actionPanel, "action"); + _card.show(this, "action"); + _currentPanel = panel; + } else { + if (_currentPanel == _actionPanel) { + _actionPanel.setVisible(false); + remove(_actionPanel); + } + _card.show(this, "edit"); + _currentPanel = panel; + } + } + + + /** + * Methods for busy status set /clear + * + */ + + /** + * Find the current ResourcePage in the current Frame + */ + private static Framework getActiveFrame(Component c) { + Framework activeFrame = null; + if (c != null) { + activeFrame = (Framework) SwingUtilities.getAncestorOfClass( + Framework.class, c); + } + if (activeFrame == null) { + activeFrame = + (Framework) UtilConsoleGlobals.getActivatedFrame(); + } + return activeFrame; + } + + /** + * Set progress indicators + * + */ + public static void setProgressIndicator(Component c, String text, + int total, int done) { + + DialogFrame dialog = + (DialogFrame) SwingUtilities.getAncestorOfClass( + DialogFrame.class, c); + if (dialog != null) { + dialog.setBusyCursor(true); + } + Framework activeFrame = getActiveFrame(c); + if (activeFrame == null) + return; + + Integer proc = StatusItemProgress.STATE_BUSY; + + if (total > 0) { + proc = new Integer ((total == done) ? 100 : + (int)((done * 100.) / total)); + } + + activeFrame.setBusyCursor(true); + activeFrame.changeStatusItemState(Framework.STATUS_TEXT, text); + activeFrame.changeStatusItemState(ResourcePage.STATUS_PROGRESS, + proc); + } + + + /** + * Clear progress indicators + * + */ + public static void clearProgressIndicator(Component c) { + DialogFrame dialog = + (DialogFrame) SwingUtilities.getAncestorOfClass( + DialogFrame.class, c); + if (dialog != null) { + dialog.setBusyCursor(false); + } + Framework activeFrame = getActiveFrame(c); + if (activeFrame == null) + return; + + activeFrame.setBusyCursor(false); + activeFrame.changeStatusItemState(Framework.STATUS_TEXT, ""); + activeFrame.changeStatusItemState(ResourcePage.STATUS_PROGRESS, + new Integer(0)); + } +} diff --git a/src/com/netscape/management/admserv/config/ButtonBar.java b/src/com/netscape/management/admserv/config/ButtonBar.java new file mode 100644 index 0000000..9018ec9 --- /dev/null +++ b/src/com/netscape/management/admserv/config/ButtonBar.java @@ -0,0 +1,256 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.awt.*; +import java.awt.event.*; +import java.util.Vector; +import javax.swing.*; +import javax.swing.border.*; +import com.netscape.management.client.util.*; +import com.netscape.management.nmclf.SuiLookAndFeel; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ + +/** + * Create a command button bar. The main purpose of this class is to privide consistent + * look for buutons. By default, button bar has OK, Cancel and Help buttons. Inside + * a dialog, Close button is also added. The button bar can have horizonal or vertical + * orientation. A reference to a button can be obtained by it's command string. Action + * Listener on the ButtonBar receives action events triggered by any of the buttons. + * The particular button command string should be used to differenciate the buttons. + */ +public class ButtonBar extends JPanel { + + static ResourceSet _resource; + static public String _i18nOKButton, _i18nCancelButton, + _i18nCloseButton, _i18nHelpButton; + static public String _i18nSaveButton, _i18nResetButton, + _i18nSaveToolTip, _i18nResetToolTip, _i18nHelpToolTip; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.config.config"); + _i18nOKButton = _resource.getString("common", "OKButton"); + _i18nCancelButton = _resource.getString("common", "CancelButton"); + _i18nCloseButton = _resource.getString("common", "CloseButton"); + _i18nSaveButton = _resource.getString("common", "SaveButton"); + _i18nResetButton = _resource.getString("common", "ResetButton"); + _i18nHelpButton = _resource.getString("common", "HelpButton"); + _i18nSaveToolTip = _resource.getString("common", "SaveToolTip"); + _i18nResetToolTip = _resource.getString("common", "ResetToolTip"); + _i18nHelpToolTip = _resource.getString("common", "HelpToolTip"); + } + + /** + * Standard Command Buttons + */ + public static final String cmdOK = "ok", cmdCancel = "cancel", + cmdClose = "close", cmdHelp = "help"; + + protected Vector _buttons = new Vector(5); + + // Standard panel commands buttons OK, Cancel, Help + static private String[] stdCommands = { cmdOK, cmdCancel, null, + cmdHelp}; + static private String[] stdLabels = { _i18nSaveButton, + _i18nResetButton, null, _i18nHelpButton }; + + static private String[] stdToolTips = { _i18nSaveToolTip, + _i18nResetToolTip, null, _i18nHelpToolTip}; + + // Standard panel command buttons when running inside a dialog. All standard + Close button + static private String[] stdDialogCommands = { cmdOK, cmdCancel, + null, cmdHelp}; + static private String[] stdDialogLabels = { _i18nOKButton, + _i18nCancelButton, null, _i18nHelpButton }; + + /** + * No-Arg constructor, create default button bar, horizontal orientation + */ + public ButtonBar() { + this(stdCommands, stdLabels, true); + } + + /** + * Construct default button bar for dailog panel, horizontal orientation + * @param isDialog A flag whether the panel that create ButtonBar runs inside a dialog + */ + public ButtonBar(boolean isDialog) { + this(isDialog ? stdDialogCommands : stdCommands, + isDialog ? stdDialogLabels : stdLabels, true); + } + + /** + * Construct default button bar for dailog panel, horizontal orientation + * @param isDialog A flag whether the panel that create ButtonBar runs inside a dialog + * @param toolTips Customized tool tips + */ + public ButtonBar(boolean isDialog, String[] toolTips) { + this(isDialog ? stdDialogCommands : stdCommands, + isDialog ? stdDialogLabels : stdLabels, toolTips, true); + } + + /** + * The generic button bar constrator. Enabels for constructon of custom button bars. + * null as a command/label has a special meaning: Start a new button group. In + * that case, a bigger spacing is aplied to the next button's left (horizontal bar) or + * top (vertical bar) inset in accordance with the Kingpin L&F style guide + * @param commands Array of command string for the buttons + * @param labels Array of labels for the buttons + * @param isHorizontal A flag whether the button bar has horzontal orientation + * @exception IllegalArgumentException Length of commands and lebels + * arrays are not the same + */ + public ButtonBar(String[] commands, String[] labels, boolean isHorizontal) { + this(commands, labels, stdToolTips, isHorizontal); + } + + /** + * The generic button bar constrator. Enabels for constructon of custom button bars. + * null as a command/label has a special meaning: Start a new button group. In + * that case, a bigger spacing is aplied to the next button's left (horizontal bar) or + * top (vertical bar) inset in accordance with the Kingpin L&F style guide + * @param commands Array of command string for the buttons + * @param labels Array of labels for the buttons + * @param toolTips Array of tool tips for the buttons + * @param isHorizontal A flag whether the button bar has horzontal orientation + * @exception IllegalArgumentException Length of commands and labels + * arrays are not the same + */ + public ButtonBar(String[] commands, String[] labels, String[] toolTips, boolean isHorizontal) { + + JButton button; + JPanel p = new JPanel(); + GBC gbc = new GBC(); + + if ((commands.length != labels.length) + && (commands.length != toolTips.length)) { + throw new IllegalArgumentException( + "In Constructor ButtonBar(): commands.length=" + + commands.length + ",labels.length=" + labels.length + + ",toolTips.length=" + toolTips.length); + } + + setLayout(new GridBagLayout()); + p.setLayout (new GridBagLayout()); + + int gridx = 0, gridy = 0, insetTop = 0, insetLeft = 0, + insetBottom = 0, insetRight = 0; + boolean newButtonGroup = false; + + JButton[] factoryButtons = JButtonFactory.create(labels); + + for (int i = 0; i < labels.length; i++) { + + if (labels[i] == null) { + newButtonGroup = true; + continue; + } + + _buttons.addElement(button = factoryButtons[i]); + button.setActionCommand(commands[i]); + JButtonFactory.initializeMnemonic(button); + button.setToolTipText(toolTips[i]); + + /* + * Apply the proper button spacing. If start of a new button group + * use SEPARATED_COMPONENT_SPACE + */ + insetTop = insetLeft = insetBottom = insetRight = 0; + if (isHorizontal) { + if (i != 0) { + if (newButtonGroup) { + insetLeft = + SuiLookAndFeel.SEPARATED_COMPONENT_SPACE; + } else { + insetLeft = SuiLookAndFeel.COMPONENT_SPACE; + } + } + } else { + if (i != 0) { + if (newButtonGroup) { + insetTop = SuiLookAndFeel.SEPARATED_COMPONENT_SPACE; + } else { + insetTop = SuiLookAndFeel.COMPONENT_SPACE; + } + } + } + + gbc.setInsets(insetTop, insetLeft, insetBottom, insetRight); + gbc.setGrid(gridx, gridy, 1, 1); + gbc.setSpace(1.0, 0.0, /*anchor=*/GBC.CENTER, + /*fill=*/GBC.NONE); + p.add(button, gbc); + + if (isHorizontal) { + gridx++; + } else { + gridy++; + } + newButtonGroup = false; + } + + /** + * Add the buttons to the panel right left conner + */ + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(1.0, 0.0, /*anchor=*/GBC.EAST, /*fill=*/GBC.NONE); + add(p, gbc); + } + + /** + * Get a button with the command string command + */ + public JButton getButton(String command) { + for (int i = 0; i < _buttons.size(); i++) { + JButton button = (JButton)_buttons.elementAt(i); + if (button.getActionCommand().equals(command)) { + return button; + } + } + return null; + } + + /** + * Add listener too all buttons + */ + public void addActionListener(ActionListener listener) { + for (int i = 0; i < _buttons.size(); i++) { + JButton button = (JButton)_buttons.elementAt(i); + button.addActionListener(listener); + } + } + + /** + * Remove action listener on all buttons + */ + public void removeActionListener(ActionListener listener) { + for (int i = 0; i < _buttons.size(); i++) { + JButton button = (JButton)_buttons.elementAt(i); + button.removeActionListener(listener); + } + } +} diff --git a/src/com/netscape/management/admserv/config/ConfigErrorDialog.java b/src/com/netscape/management/admserv/config/ConfigErrorDialog.java new file mode 100644 index 0000000..48ac373 --- /dev/null +++ b/src/com/netscape/management/admserv/config/ConfigErrorDialog.java @@ -0,0 +1,143 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.border.*; +import com.netscape.management.nmclf.*; +import com.netscape.management.client.util.*; +import com.netscape.management.nmclf.SuiLookAndFeel; + +/** + * Error Dialog for Config Exceptions +*/ +public class ConfigErrorDialog { + + static ResourceSet _resource; + static String _i18nDefaultTitle, _i18nValidationError, _i18nRemoteRequestError; + static String _i18nURL, _i18nDataItem, _i18nDN, _i18nMatchedDN; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.config.config"); + _i18nDefaultTitle = _resource.getString("errdialog", "DefaultTitle"); + _i18nValidationError = _resource.getString("errdialog", "ValidationError"); + _i18nRemoteRequestError = _resource.getString("errdialog", "RemoteRequestError"); + _i18nURL = _resource.getString("errdialog", "URL"); + _i18nDN = _resource.getString("errdialog", "DN"); + _i18nMatchedDN = _resource.getString("errdialog", "MatchedDN"); + _i18nDataItem = _resource.getString("errdialog", "DataItem"); + } + + + public static void showDialog(Component parent, + ConfigPanelException e) { + String title = _i18nDefaultTitle; + String msg = ""; + ConfigErrorDialog dialog = null; + Frame frame = getParentFrame(parent); + + BaseConfigPanel.clearProgressIndicator(parent); + + if (e instanceof ValidationException) { + title = _i18nValidationError; + msg = e.getMessage(); + //dialog = new ConfigErrorDialog(parent, title, e); + } else if (e instanceof RemoteRequestException) { + RemoteRequestException ex = (RemoteRequestException) e; + title = _i18nRemoteRequestError; + + if (ex.getType() == RemoteRequestException.LDAP) { + msg = _i18nDN + ex.getDN() + "\n" + _i18nMatchedDN + + ex.getMatchedDN() + "\n\n" + ex.getMessage(); + } else { + String url = ex.getURL(); + if (url.indexOf("?") > 0) { + url = url.substring(0, url.indexOf("?")); + } + msg = _i18nURL + url + "\n\n" + ex.getMessage(); + } + + } + + ActionMonitorPanel actionPanel = + ActionMonitorPanel.getActiveInstance(); + if (actionPanel != null) + actionPanel.setInterruptEnabled(false); + + if (Thread.currentThread().getClass().getName().equals("java.awt.EventDispatchThread")) { + SuiOptionPane.showMessageDialog(frame, msg, title, + SuiOptionPane.ERROR_MESSAGE); + } else { + final String title_f = title, msg_f = msg; + final Frame frame_f = frame; + + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + SuiOptionPane.showMessageDialog( + frame_f, msg_f, title_f, + SuiOptionPane.ERROR_MESSAGE); + } + } + ); + } catch (Exception e1) { + Debug.println("showDialog invokeAndWait " + e1); + } + } + + + if (actionPanel != null) + actionPanel.setInterruptEnabled(true); + } + + + // In case NULL of not visible components are passed as a parent to showDialog(), + // we create an helper Window to use as a parent. + private static Window _helperWindow; + + + // Return parent Frame. If one does not exist, create a helper Window. + // We use a Window insead of Frame bacause it can be undetecable on the screen + // by setting its size to [0,0]. Frame always has a visible title bar. + public static Frame getParentFrame(Component c) { + Frame f = SuiOptionPane.getFrameForComponent(c); + + if (f == null) + f = UtilConsoleGlobals.getActivatedFrame(); + + if (f == null) { + if (_helperWindow == null) { + _helperWindow = new Window (new Frame()); + } + return (Frame)_helperWindow.getParent(); + } else { + return f; + } + } + + + + +} diff --git a/src/com/netscape/management/admserv/config/ConfigInfoDialog.java b/src/com/netscape/management/admserv/config/ConfigInfoDialog.java new file mode 100644 index 0000000..220c9ac --- /dev/null +++ b/src/com/netscape/management/admserv/config/ConfigInfoDialog.java @@ -0,0 +1,81 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.border.*; +import com.netscape.management.client.util.*; +import com.netscape.management.nmclf.SuiLookAndFeel; + +/** + * Error Dialog for Config Exceptions +*/ +public class ConfigInfoDialog { + + static ResourceSet _resource; + static String _i18nDefaultTitle; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.config.config"); + _i18nDefaultTitle = _resource.getString("infodialog", "DefaultTitle"); + } + + private Component _parent; + private ButtonBar _buttons; + private Font _fontLabel = UIManager.getFont("Panel.font"); + + public static void showDialog(Component parent, String text, + String title) { + Frame frame = ConfigErrorDialog.getParentFrame(parent); + + BaseConfigPanel.clearProgressIndicator(parent); + + if (title == null || title.length() == 0) { + title = _i18nDefaultTitle; + } + + if (Thread.currentThread().getClass().getName().equals("java.awt.EventDispatchThread")) { + JOptionPane.showMessageDialog(frame, text, title, + JOptionPane.INFORMATION_MESSAGE); + } else { + final String title_f = title, text_f = text; + final Frame frame_f = frame; + + try { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + JOptionPane.showMessageDialog(frame_f, + text_f, title_f, + JOptionPane.INFORMATION_MESSAGE); + } + } + ); + } catch (Exception e1) { + Debug.println("showDialog invokeAndWait " + e1); + } + } + + } +} diff --git a/src/com/netscape/management/admserv/config/ConfigPanelException.java b/src/com/netscape/management/admserv/config/ConfigPanelException.java new file mode 100644 index 0000000..2ed7845 --- /dev/null +++ b/src/com/netscape/management/admserv/config/ConfigPanelException.java @@ -0,0 +1,27 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +/** + * A common umbrella for config related exceptions +*/ +public class ConfigPanelException extends Exception { +} diff --git a/src/com/netscape/management/admserv/config/EditMonitor.java b/src/com/netscape/management/admserv/config/EditMonitor.java new file mode 100644 index 0000000..d6bd8c0 --- /dev/null +++ b/src/com/netscape/management/admserv/config/EditMonitor.java @@ -0,0 +1,227 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.text.*; +import com.netscape.management.client.util.*; + +/** + * + * @version 0.1 11/26/97 + * @author miodrag@netscape.com + */ + +public class EditMonitor implements ActionListener, ChangeListener, +DocumentListener, ItemListener, ListDataListener { + + boolean _isDirty = false; + + boolean _isRunning = false; + + /** Dirty flag listeners */ + Vector _listeners; + + /** Components to be enabled when dirty flag is true */ + Vector _enableComponents; + + /** Components to be disable when dirty flag is true */ + Vector _disableComponents; + + + /** + * Constructors + */ + public EditMonitor() { + _enableComponents = new Vector(5); + _disableComponents = new Vector(5); + _listeners = new Vector(5); + } + + /** Start processing change events */ + void start() { + _isRunning = true; + } + + /** Do not process change events */ + void stop() { + _isRunning = false; + } + + /** + * Change listeners when dirty flag is modified + */ + + public void addChangeListener(ChangeListener l) { + _listeners.addElement(l); + } + + public void removeChangeListener(ChangeListener l) { + _listeners.removeElement(l); + } + + protected void fireChangeEvent() { + for (int i = 0; i < _listeners.size(); i++) { + ChangeListener l = (ChangeListener)_listeners.elementAt(i); + l.stateChanged(new ChangeEvent(new Boolean(_isDirty))); + } + } + + /** + * Getter / Setter methods + */ + public void setEnableComponets(Vector enableComponents) { + _enableComponents = new Vector(); + } + + public void setDisableComponets(Vector disableComponents) { + _disableComponents = new Vector(); + } + + public void addEnableComponent(Component c) { + //Debug.println("addEnableComponent" + c.getClass().getName()); + _enableComponents.addElement(c); + c.setEnabled(_isDirty); + } + + public void addDisableComponent(Component c) { + //Debug.println("addDisableComponent" + c.getClass().getName()); + _disableComponents.addElement(c); + c.setEnabled(!_isDirty); + } + + + private void setComponentsEnabledState(boolean flag) { + for (int i = 0; i < _enableComponents.size(); i++) { + Component c = (Component)_enableComponents.elementAt(i); + c.setEnabled(flag); + } + for (int i = 0; i < _disableComponents.size(); i++) { + Component c = (Component)_disableComponents.elementAt(i); + c.setEnabled(!flag); + } + + } + + public void setDirtyFlag(boolean flag) { + //Thread.currentThread().dumpStack(); + //Debug.println("dirtyFlag="+flag); + if (_isRunning) { + boolean modified = (flag != _isDirty); + _isDirty = flag; + setComponentsEnabledState(_isDirty); + if (modified) { + fireChangeEvent(); + } + } + } + + public boolean getDirtyFlag() { + return _isDirty; + } + + /** + * Subscription methods for monitoring changes + */ + public void monitor(JTextComponent text) { + text.getDocument().addDocumentListener(this); + } + + public void monitor(JList list) { + list.getModel().addListDataListener(this); + } + + public void monitor(ListModel model) { + model.addListDataListener(this); + } + + public void monitor(JToggleButton toggle) { + toggle.addActionListener(this); + } + + public void monitor(JComboBox comboChoice) { + comboChoice.addItemListener(this); + } + + /** + * Listener interface implementation + */ + + // Action + public void actionPerformed(ActionEvent e) { + if (e.getSource() instanceof Component) { + Component c = (Component) e.getSource(); + if (c.isEnabled()) { + setDirtyFlag(true); + } + } else { + setDirtyFlag(true); + } + } + + // Change + public void stateChanged(ChangeEvent e) { + setDirtyFlag(true); + } + + // Document + public void changedUpdate(DocumentEvent e) { + setDirtyFlag(true); + } + public void insertUpdate(DocumentEvent e) { + setDirtyFlag(true); + } + public void removeUpdate(DocumentEvent e) { + setDirtyFlag(true); + } + + // Item + public void itemStateChanged(ItemEvent e) { + if (e.getSource() instanceof Component) { + Component c = (Component) e.getSource(); + if (c.isEnabled()) { + setDirtyFlag(true); + } + } else { + setDirtyFlag(true); + } + } + + // List Data + public void contentsChanged(ListDataEvent e) { + setDirtyFlag(true); + } + public void intervalAdded(ListDataEvent e) { + setDirtyFlag(true); + } + public void intervalRemoved(ListDataEvent e) { + setDirtyFlag(true); + } + + public String toString() { + return "EditMonitor[dirty=" + _isDirty + ", running=" + + _isRunning + "]"; + } +} diff --git a/src/com/netscape/management/admserv/config/FilteredInputDocument.java b/src/com/netscape/management/admserv/config/FilteredInputDocument.java new file mode 100644 index 0000000..f5ee677 --- /dev/null +++ b/src/com/netscape/management/admserv/config/FilteredInputDocument.java @@ -0,0 +1,75 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +/** + * A text model (document) that restrects JTextField charaters to a specified character set. It + * can be used to create, for instance, digit-only text fields, alphanumeric-only text fields, + * etc. If a non allowed character is entered by the user, the charachter does not get echoed back + * to the screen and the Console beeps. + * + * Usage example for digits only text field: + * JtextField tfPortNumber = new JTextField(); + * tfPortNumber.setDocument(new FilteredInputDocument("1234567890"); + * + * + */ + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.text.*; + +public class FilteredInputDocument extends PlainDocument { + + public static final String DIGITS = "01234567890"; + public static final String IPADDRESS = "01234567890."; + + String _allowSet; + + public FilteredInputDocument(String allowSet) { + _allowSet = allowSet; + } + + public static FilteredInputDocument allowDigitsOnly() { + return new FilteredInputDocument(DIGITS); + } + + public static FilteredInputDocument allowIPAddressOnly() { + return new FilteredInputDocument(IPADDRESS); + } + + public void insertString(int offs, String str, + AttributeSet a) throws BadLocationException { + String filtered = new String(); + for (int i = 0; i < str.length(); i++) { + if (_allowSet.indexOf(str.charAt(i)) < 0) { + Toolkit.getDefaultToolkit().beep(); + } else { + filtered += str.charAt(i); + } + } + if (filtered.length() > 0) { + super.insertString(offs, filtered, a); + } + } +} diff --git a/src/com/netscape/management/admserv/config/GBC.java b/src/com/netscape/management/admserv/config/GBC.java new file mode 100644 index 0000000..c487240 --- /dev/null +++ b/src/com/netscape/management/admserv/config/GBC.java @@ -0,0 +1,47 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.awt.Insets; +import java.awt.GridBagConstraints; + +public class GBC extends java.awt.GridBagConstraints { + + public void setInsets(int top, int left, int bottom, int right) { + this.insets = new Insets(top, left, bottom, right); + } + + public void setGrid(int x, int y, int w, int h) { + this.gridx = x; + this.gridy = y; + this.gridwidth = w; + this.gridheight = h; + } + + public void setSpace(double weightx, double weighty, int anchor, + int fill) { + this.weightx = weightx; + this.weighty = weighty; + this.anchor = anchor; + this.fill = fill; + } +} + diff --git a/src/com/netscape/management/admserv/config/IConfigDataModel.java b/src/com/netscape/management/admserv/config/IConfigDataModel.java new file mode 100644 index 0000000..22ffd96 --- /dev/null +++ b/src/com/netscape/management/admserv/config/IConfigDataModel.java @@ -0,0 +1,76 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +/** + * A generic interface for config dialog data model + */ +public interface IConfigDataModel { + + /** + * Returns true id data model is loaded with server data + */ + public boolean isLoaded(); + + /** + * Load data model from the server + * @exception RemoteRequestException + */ + public void load() throws RemoteRequestException; + + /** + * Returns true is data model is modified + */ + public boolean isModified(); + + /** + * Save data model to the server + * @exception RemoteRequestException + */ + public void save() throws RemoteRequestException; + + /** + * Returns enumeration for attributes + * @return Enumeration for attributes + */ + public java.util.Enumeration getAttributes(); + + /** + * Get Value for the attribute with the specified name + * @param attr the name of an attribute + * @return value for the attribute + */ + public String getAttribute(String attr); + + /** + * Set the value for an attribute + * @param attr the name for an attribute + * @param val the value for the attribute + */ + public void setAttribute(String attr, + String val) throws ValidationException; + + /** + * Return the model name. This can be the server name. + * @return the identifier for the data model + */ + public String getModelName(); +} diff --git a/src/com/netscape/management/admserv/config/IPluginConfigPanel.java b/src/com/netscape/management/admserv/config/IPluginConfigPanel.java new file mode 100644 index 0000000..9f1fd9a --- /dev/null +++ b/src/com/netscape/management/admserv/config/IPluginConfigPanel.java @@ -0,0 +1,86 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ + +public interface IPluginConfigPanel { + + /** + * Returns the title for the panel. + */ + public String getTitleText(); + + /** + * Returns the reference to the panel + */ + public javax.swing.JPanel getPanel(); + + /** + * Returns the data model for the panel + */ + public IConfigDataModel getDataModel(); + + /** + * Set data model for the panel. The panel can swith data model dynamically. + * + * @param dataModel A data model for the panel + */ + public void setDataModel(IConfigDataModel datModel) + throws ConfigPanelException; + + /** + * Called to initialize the panel content. This method should be used to + * load the model if necessary and populate the panel with the model data. The + * panel layout should be created in the constructor, so that panel can be created + * before data are loaded + */ + public void initialize() throws ConfigPanelException; + + /** + * Register ui components that modify data with the edit monitor. The + * edit monitor encapsulates 'dirty' flag and enables button bar buttons + * if data are modifed + */ + public void registerEditComponents(EditMonitor monitor); + + /** + * Reset panel content when 'cancel' button is applied. + */ + abstract public void resetContent() throws ConfigPanelException; + + /** + * Apply changes when panel is modified and 'ok' button is pressed. The method + * should just propagate the changes into the data model. The framework will + * invoke save operation on the model, if the model is modified. + */ + abstract public void applyChanges() throws ConfigPanelException; + + /** + * Method called when 'help' button is pressed. + */ + abstract public void showHelp(); + +} diff --git a/src/com/netscape/management/admserv/config/PluginConfigPanel.java b/src/com/netscape/management/admserv/config/PluginConfigPanel.java new file mode 100644 index 0000000..23d3f9d --- /dev/null +++ b/src/com/netscape/management/admserv/config/PluginConfigPanel.java @@ -0,0 +1,61 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.awt.*; +import java.util.*; +import javax.swing.*; +import javax.swing.border.*; +import com.netscape.management.nmclf.SuiLookAndFeel; +import com.netscape.management.client.util.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ + +public abstract class PluginConfigPanel extends JPanel implements IPluginConfigPanel { + + private String _titleText = ""; + + public PluginConfigPanel() { + this(""); + } + + public PluginConfigPanel(String title) { + //setBorder(new EmptyBorder(0,5,0,5)); + _titleText = title; + } + + public JPanel getPanel() { + return this; + } + + public String getTitleText() { + return _titleText; + } + + public void showHelp() { + Debug.println("help not implemented"); + } + +} diff --git a/src/com/netscape/management/admserv/config/RemoteRequestException.java b/src/com/netscape/management/admserv/config/RemoteRequestException.java new file mode 100644 index 0000000..fece06d --- /dev/null +++ b/src/com/netscape/management/admserv/config/RemoteRequestException.java @@ -0,0 +1,89 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.net.URL; +import com.netscape.management.client.comm.HttpException; +import netscape.ldap.LDAPException; + +public class RemoteRequestException extends ConfigPanelException { + + public static final int HTTP = 0; + public static final int LDAP = 1; + + private int _type = HTTP; + private String _url, _dn , _matchedDN; + private String _message; + + public RemoteRequestException(String url, String message) { + _url = url; + _message = message; + _type = HTTP; + } + + public RemoteRequestException(HttpException e) { + _url = e.getURL().toString(); + _message = e.getStatus(); + _type = HTTP; + } + + public RemoteRequestException(LDAPException e, String dn) { + _dn = dn; + _matchedDN = e.getMatchedDN(); + _message = e.toString(); + _type = LDAP; + } + + public RemoteRequestException(Exception e) { + if (e instanceof HttpException) { + _url = ((HttpException) e).getURL().toString(); + _message = ((HttpException) e).getStatus(); + } else { + _url = ""; + _message = e.getMessage(); + } + } + + public int getType() { + return _type; + } + + public String getURL() { + return _url; + } + + public String getDN() { + return _dn; + } + + public String getMatchedDN() { + return _matchedDN; + } + + public String getMessage() { + return _message; + } + + public String toString() { + return "RemoteRequestException:\n" + "Message: " + _message + + "\n" + "URL: " + _url; + } +} diff --git a/src/com/netscape/management/admserv/config/TabbedConfigPanel.java b/src/com/netscape/management/admserv/config/TabbedConfigPanel.java new file mode 100644 index 0000000..907b08c --- /dev/null +++ b/src/com/netscape/management/admserv/config/TabbedConfigPanel.java @@ -0,0 +1,290 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +import java.awt.*; +import java.util.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.border.*; +import com.netscape.management.client.util.*; +import com.netscape.management.nmclf.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ + + +/** + * A tabbed pane which contains multiple PluginConfigPanels and behaves itself like + * a PluginConfigPanel. It supports immediate or lazy creation mode of panels. + * If the lazy creation mode is selected, a panel is created the first time its tab is + * clicked. + */ +public abstract class TabbedConfigPanel extends PluginConfigPanel { + + /** + * Creation modes : immediate (default) or lazy + */ + public static final int IMMEDIATE_CREATE = 0; + public static final int LAZY_CREATE = 1; + + int _createMode = IMMEDIATE_CREATE; + + Vector _tabs = new Vector(); + JTabbedPane _tabbedPane; + public static Object _notCreatedTab; + EditMonitor _editMonitor; + + + /** + * Constructors + */ + public TabbedConfigPanel() { + this(IMMEDIATE_CREATE); + } + + public TabbedConfigPanel(int createMode) { + _createMode = createMode; + setLayout(new BorderLayout()); + setBorder(new EmptyBorder(0, 0, 0, 0)); + + _tabbedPane = new JTabbedPane(); + try { + _tabbedPane.setTabLayoutPolicy(_tabbedPane.SCROLL_TAB_LAYOUT); + } + catch (Throwable ignore) { + //setTabLayoutPolicy is a JDK1.4 call, allow older JVMs + } + add(_tabbedPane, BorderLayout.CENTER); + if (_createMode == LAZY_CREATE) { + _tabbedPane.addChangeListener(_tabListener); + } + } + + + /** + * Return a vector of tab panels + */ + public Vector getTabs() { + return _tabs; + } + + /** + * Listen for tab selection changes + */ + ChangeListener _tabListener = new ChangeListener() { + public void stateChanged(ChangeEvent e) { + tabSelected(_tabbedPane.getSelectedIndex()); + } + }; + + /** + * Callback when tab is selected. Create a tab if not already created + * (lazy mode) + */ + protected void tabSelected(int idx) { + if (_tabs.elementAt(idx) == _notCreatedTab) { + BaseConfigPanel bcp = BaseConfigPanel.getInstance(_tabbedPane); + if (bcp != null) + bcp.monitorLongAction(new CreateTabAction(idx)); + else + (new CreateTabAction(idx)).run(); + } else { + // Enable help button a for loaded tab + enableHelpButton(true); + } + + } + + /** + * Create a new tab (lazy mode) + */ + class CreateTabAction implements Runnable { + int idx; + public CreateTabAction(int idx) { + this.idx = idx; + } + public void run() { + setActionCursor( + Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + enableHelpButton(false); + IPluginConfigPanel tab = lazyModeCreateTab(idx); + + try { + tab.initialize(); + } catch (ConfigPanelException e) { + ConfigErrorDialog.showDialog(_tabbedPane, e); + return; + } + finally { setActionCursor( + Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } tab.registerEditComponents(_editMonitor); + _tabs.setElementAt(tab, idx); + enableHelpButton(true); + + JPanel p = tab.getPanel(); + int insetH = SuiLookAndFeel.HORIZ_WINDOW_INSET; + int insetV = SuiLookAndFeel.VERT_WINDOW_INSET; + p.setBorder(new EmptyBorder(insetV, insetH, insetV, insetH)); + JScrollPane scrollPane = new JScrollPane(tab.getPanel()); + scrollPane.setBorder(BorderFactory.createEmptyBorder()); + _tabbedPane.setComponentAt(idx, scrollPane); + + } + } + + + /** + * Add a tab to the panel + */ + public void addTab(String title, ImageIcon icon, + IPluginConfigPanel tab) { + _tabs.addElement(tab); + JPanel p = tab.getPanel(); + int insetH = SuiLookAndFeel.HORIZ_WINDOW_INSET; + int insetV = SuiLookAndFeel.VERT_WINDOW_INSET; + p.setBorder(new EmptyBorder(insetV, insetH, insetV, insetH)); + JScrollPane scrollPane = new JScrollPane(p); + scrollPane.setBorder(BorderFactory.createEmptyBorder()); + _tabbedPane.addTab(title, icon, scrollPane); + } + + /** + * Reserve a tab do not create it (lazy mode) + */ + public int lazyModeReserveTab(String title, ImageIcon icon) { + _tabbedPane.addTab(title, icon, new JLabel(" ")); + _tabs.addElement(_notCreatedTab); + return _tabs.size() - 1; + } + + /** + * If lazy creation is selected this method must be overriden to create a panel + * when a tab is clicked for the first time. + */ + public IPluginConfigPanel lazyModeCreateTab(int idx) { + throw new Error("Not implemented"); // must be overriden if lazy mode used + } + + // By default, tabbed panels do not have a title + // Implements IpluginConfigPanel.getTitleText() + public String getTitleText() { + return null; + } + + // Implements IpluginConfigPanel.initialize() + public void initialize() throws ConfigPanelException { + for (int i = 0; i < _tabs.size(); i++) { + if (_tabs.elementAt(i) == _notCreatedTab) + continue; + IPluginConfigPanel tab = (IPluginConfigPanel)_tabs.elementAt(i); + tab.initialize(); + } + + //Debug.println("tab count = " + _tabbedPane.getTabCount() + " " + Thread.currentThread().getName()); + _tabbedPane.setSelectedIndex(0); + _tabbedPane.validate(); + _tabbedPane.repaint(); + } + + // Implements IpluginConfigPanel.setDataModel() + public void setDataModel(IConfigDataModel dataModel) + throws ConfigPanelException { + for (int i = 0; i < _tabs.size(); i++) { + if (_tabs.elementAt(i) == _notCreatedTab) + continue; + IPluginConfigPanel tab = (IPluginConfigPanel)_tabs.elementAt(i); + tab.setDataModel(dataModel); + } + } + + // Implements IpluginConfigPanel.registerEditComponents() + public void registerEditComponents(EditMonitor monitor) { + _editMonitor = monitor; + for (int i = 0; i < _tabs.size(); i++) { + if (_tabs.elementAt(i) == _notCreatedTab) + continue; + IPluginConfigPanel tab = (IPluginConfigPanel)_tabs.elementAt(i); + tab.registerEditComponents(monitor); + } + } + + // implements IpluginConfigPanel.resetContent() + public void resetContent() throws ConfigPanelException { + for (int i = 0; i < _tabs.size(); i++) { + if (_tabs.elementAt(i) == _notCreatedTab) + continue; + IPluginConfigPanel tab = (IPluginConfigPanel)_tabs.elementAt(i); + tab.resetContent(); + } + } + + // Implements IpluginConfigPanel.applyChanges() + public void applyChanges() throws ConfigPanelException { + for (int i = 0; i < _tabs.size(); i++) { + if (_tabs.elementAt(i) == _notCreatedTab) + continue; + IPluginConfigPanel tab = (IPluginConfigPanel)_tabs.elementAt(i); + tab.applyChanges(); + } + } + + // implements IpluginConfigPanel.showHelp() + public void showHelp() { + IPluginConfigPanel tab = (IPluginConfigPanel)_tabs.elementAt( + _tabbedPane.getSelectedIndex()); + if (tab != _notCreatedTab) { + tab.showHelp(); + } + } + + /** + * Change the cursor on the top-most window + */ + protected void setActionCursor(Cursor cursor) { + Component c = _tabbedPane; + while (c != null && + ! (c instanceof JFrame || c instanceof JDialog)) { + c = c.getParent(); + } + if (c != null) { + c.setCursor(cursor); + } + } + + /** + * Change the state of the help button on the base panel's button bar + */ + protected void enableHelpButton(boolean flag) { + BaseConfigPanel bcp = BaseConfigPanel.getInstance(_tabbedPane); + if (bcp != null) { + if (bcp.getCommandButtonBar() != null) { + JButton helpButton = bcp.getCommandButtonBar().getButton( + ButtonBar.cmdHelp); + helpButton.setEnabled(flag); + } + } + } +} diff --git a/src/com/netscape/management/admserv/config/ValidationException.java b/src/com/netscape/management/admserv/config/ValidationException.java new file mode 100644 index 0000000..7cbc34b --- /dev/null +++ b/src/com/netscape/management/admserv/config/ValidationException.java @@ -0,0 +1,45 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.config; + +public class ValidationException extends ConfigPanelException { + + private String _item; + private String _message; + + public ValidationException(String item, String message) { + _item = item; + _message = message; + } + + public String getItem() { + return _item; + } + + public String getMessage() { + return _message; + } + + public String toString() { + return "ValidationException:\n" + "Message: " + _message + + "\n" + "Item: " + _item; + } +} diff --git a/src/com/netscape/management/admserv/config/config.properties b/src/com/netscape/management/admserv/config/config.properties new file mode 100644 index 0000000..b68f809 --- /dev/null +++ b/src/com/netscape/management/admserv/config/config.properties @@ -0,0 +1,62 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# + +# END COPYRIGHT BLOCK +# config package properties + +common-OKButton=&OK +common-CancelButton=&Cancel +common-CloseButton=&Close +common-SaveButton=&Save +common-ResetButton=&Reset +common-HelpButton=&Help +common-SaveToolTip=Save +common-ResetToolTip=Reset +common-HelpToolTip=Help + +# +# Action Monitor Panel +# +actionmon-ActionAborted=Action Cancelled +actionmon-TooltipInterrupt=Interrupt the action + +# +# Config Error Dialog +# +errdialog-ValidationError=Validation Error +errdialog-RemoteRequestError=Remote Request Error +errdialog-DataItem=Data Item: +errdialog-URL=URL: +errdialog-DN=DN: +errdialog-MatchedDN=Matched DN: +errdialog-DefaultTitle=Error + +infodialog-DefaultTitle=Status Information + +# +# Base Config Panel +# +baseconfig-StatusLoading=Loading ... +baseconfig-StatusSaving=Saving ... +baseconfig-LoadFailed=Failed to load data +baseconfig-SaveToolTip=Save current Configuration +baseconfig-ResetToolTip=Reset to previously saved Configuration +baseconfig-HelpToolTip=Launch Help for this view + diff --git a/src/com/netscape/management/admserv/images/AdminServer.gif b/src/com/netscape/management/admserv/images/AdminServer.gif new file mode 100644 index 0000000..61ed8a9 Binary files /dev/null and b/src/com/netscape/management/admserv/images/AdminServer.gif differ diff --git a/src/com/netscape/management/admserv/images/AdminServerL.gif b/src/com/netscape/management/admserv/images/AdminServerL.gif new file mode 100644 index 0000000..c4925a3 Binary files /dev/null and b/src/com/netscape/management/admserv/images/AdminServerL.gif differ diff --git a/src/com/netscape/management/admserv/images/admin.gif b/src/com/netscape/management/admserv/images/admin.gif new file mode 100644 index 0000000..4489dfe Binary files /dev/null and b/src/com/netscape/management/admserv/images/admin.gif differ diff --git a/src/com/netscape/management/admserv/images/admin50.gif b/src/com/netscape/management/admserv/images/admin50.gif new file mode 100644 index 0000000..606d01a Binary files /dev/null and b/src/com/netscape/management/admserv/images/admin50.gif differ diff --git a/src/com/netscape/management/admserv/logging/AccessLogViewerModel.java b/src/com/netscape/management/admserv/logging/AccessLogViewerModel.java new file mode 100644 index 0000000..535a1d1 --- /dev/null +++ b/src/com/netscape/management/admserv/logging/AccessLogViewerModel.java @@ -0,0 +1,310 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.logging; + +import java.io.*; +import java.util.*; +import java.net.*; +import javax.swing.table.*; +import com.netscape.management.client.comm.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.logging.*; +import com.netscape.management.client.util.*; +import com.netscape.management.admserv.*; + +public class AccessLogViewerModel extends LogViewerModel { + ConsoleInfo _consoleInfo; + String _url; + String _username; + String _password; + int _logLength = 0; + private boolean _isInitialized = false; + public boolean _logLengthAvailable = false; + public boolean _logLengthCalculating = false; + public StringBuffer _logLengthStringBuffer = null; + public static ResourceSet _resource = AdminServer._resource; + + public AccessLogViewerModel(ConsoleInfo consoleInfo, String url) { + super(); + _consoleInfo = consoleInfo; + //_url = "http://gumby.mcom.com:666/admin-serv/tasks/Configuration/ReadLog"; //_consoleInfo.getAdminURL() + url; + //_username = "uid=admin, ou=People, o=airius.com"; //_consoleInfo.getAuthenticationDN(); + //_password = "admin"; //_consoleInfo.getAuthenticationPassword(); + _url = _consoleInfo.getAdminURL() + url; + _username = _consoleInfo.getAuthenticationDN(); + _password = _consoleInfo.getAuthenticationPassword(); + + addColumn(_resource.getString("log", "lineno")); + addColumn(_resource.getString("log", "host")); + addColumn(_resource.getString("log", "username")); + addColumn(_resource.getString("log", "date")); + addColumn(_resource.getString("log", "time")); + addColumn(_resource.getString("log", "header")); + addColumn(_resource.getString("log", "errorcode")); + addColumn(_resource.getString("log", "length")); + _isInitialized = true; + } + + public void populateRows(int rowStartIndex, int numRows) { + Debug.println(6, + "AccessLogViewer: populateRows " + rowStartIndex + + " to " + (rowStartIndex + numRows)); + try { + URL url = new URL(_url + "?op=read" + "&start=" + + rowStartIndex + "&stop=" + + (rowStartIndex + numRows) + "&" + + URLEncoder.encode("name=../../../../admin-serv/logs/access")); + HttpManager _httpManager = new HttpManager(); + AccessDataCommClient commClient = + new AccessDataCommClient(this, _username, _password); + _httpManager.get(url, commClient, (ILogViewerModel) this, + CommManager.ASYNC_RESPONSE | + CommManager.FORCE_BASIC_AUTH); + } catch (Exception e) { + Debug.println(4, "AccessLogViewer: populateRows() " + e); + } + } + + + + /** + * Returns the number of rows in log file + */ + public int getLogLength() { + if (!_isInitialized) + return -1; + + long _currentTimeMillis = System.currentTimeMillis(); + if (((_currentTimeMillis - _lastLogLengthCheckTime) > + UPDATE_INTERVAL) && !_logLengthCalculating) { + _lastLogLengthCheckTime = _currentTimeMillis; + try // to update _logLength + { + _logLengthCalculating = true; + _logLengthAvailable = false; + _logLengthStringBuffer = new StringBuffer(); + URL url = new URL(_url + "?op=count" + "&" + + URLEncoder.encode("name=../../../../admin-serv/logs/access")); + HttpManager _httpManager = new HttpManager(); + LogLengthCommClient commClient = + new AccessLogLengthCommClient(this, _username, _password); + _httpManager.get(url, commClient, _logLengthStringBuffer, + CommManager.ASYNC_RESPONSE | + CommManager.FORCE_BASIC_AUTH); + } catch (Exception e) { + _logLengthCalculating = false; + Debug.println(4, "AccessLogViewer: getLogLength(): " + e); + } + } + + if (_logLengthAvailable) { + try { + _logLength = Integer.parseInt( + _logLengthStringBuffer.toString()); + Debug.println(6, + "AccessLogViewer: _logLength=" + _logLength); + } catch (NumberFormatException e) { + Debug.println(4, + "AccessLogViewer: Cannot convert log length: " + + _logLengthStringBuffer.toString()); + } + } + + return _logLength; + } + +} + +// Having AccessLogData as an inner-class of AccessLogViewerModel causes +// compilation errors on NT when the build tree is sufficiently deep. +// for example: D:\admin\admin50\builds\20000326.1\ztNT4.0\ +class AccessLogData { + StringBuffer host = new StringBuffer(); + StringBuffer username = new StringBuffer(); + StringBuffer date = new StringBuffer(); + StringBuffer time = new StringBuffer(); + StringBuffer header = new StringBuffer(); + StringBuffer httpcode = new StringBuffer(); + StringBuffer datalength = new StringBuffer(); +} + +// Having AccessDataCommClient as an inner-class of AccessLogViewerModel causes +// compilation errors on NT when the build tree is sufficiently deep. +// for example: D:\admin\admin50\builds\20000326.1\ztNT4.0\ +class AccessDataCommClient extends AbstractCommClient { + final int STATE_HOST = 0; + final int STATE_USERNAME = 1; + final int STATE_DATE = 2; + final int STATE_TIME = 3; + final int STATE_PRE_HEADER = 4; + final int STATE_HEADER = 5; + final int STATE_PRE_HTTPCODE = 6; + final int STATE_HTTPCODE = 7; + final int STATE_DATALENGTH = 8; + final int STATE_EXTRA = 9; + AccessLogViewerModel model; + + public AccessDataCommClient(AccessLogViewerModel model, String username, String password) { + super(username, password); + this.model = model; + Debug.println(6, "AccessLogViewer: AccessDataCommClient."); + } + + protected AccessLogData parse(String logEntry) { + StringBuffer buffer = new StringBuffer(logEntry); + AccessLogData data = new AccessLogData(); + int bufferLength = buffer.length(); + int state = STATE_HOST; + char character; + + for (int index = 0; index < bufferLength; index++) { + character = buffer.charAt(index); + switch (state) { + case STATE_HOST: + if (character == '-') + state = STATE_USERNAME; + else if (character != ' ') + data.host.append(character); + break; + + case STATE_USERNAME: + if (character == '[') + state = STATE_DATE; + else if (character != ' ') + data.username.append(character); + break; + + case STATE_DATE: + if (character == ':') + state = STATE_TIME; + else + data.date.append(character); + break; + + case STATE_TIME: + if (character == ']') + state = STATE_PRE_HEADER; + else + data.time.append(character); + break; + + case STATE_PRE_HEADER: + if (character == '"') + state = STATE_HEADER; + break; + + case STATE_HEADER: + if (character == '"') + state = STATE_PRE_HTTPCODE; + else + data.header.append(character); + break; + + case STATE_PRE_HTTPCODE: + if (character == ' ') + state = STATE_HTTPCODE; + break; + + case STATE_HTTPCODE: + if (character == ' ') + state = STATE_DATALENGTH; + else + data.httpcode.append(character); + break; + + case STATE_DATALENGTH: + if (character == ' ') + state = STATE_EXTRA; + else + data.datalength.append(character); + break; + + + case STATE_EXTRA: + // TODO + break; + + } + } + return data; + } + + public void replyHandler(InputStream replyStream, CommRecord cr) { + BufferedReader replyBuffer = new BufferedReader( + new InputStreamReader(replyStream)); + ILogViewerModel model = (ILogViewerModel) cr.getArg(); + int rowOffset = model.getRowOffset(); + int bufferLength = model.getBufferLength(); + String logEntry = null; + for (int rowIndex = 0; rowIndex < bufferLength; rowIndex++) { + try { + logEntry = replyBuffer.readLine(); + } catch (Exception e) { + Debug.println(4, + "AccessLogViewer: replyHandler() " + e); + } + if (logEntry != null) { + AccessLogData d = parse(logEntry); + model.setValueAt( + Integer.toString(rowOffset + rowIndex), + rowIndex, 0); + model.setValueAt(d.host, rowIndex, 1); + model.setValueAt(d.username, rowIndex, 2); + model.setValueAt(d.date, rowIndex, 3); + model.setValueAt(d.time, rowIndex, 4); + model.setValueAt(d.header, rowIndex, 5); + model.setValueAt(d.httpcode, rowIndex, 6); + model.setValueAt(d.datalength, rowIndex, 7); + } else { + break; + } + } + finish(); + } + + public synchronized void finish() { + super.finish(); + model.tableDataChanged(); + Debug.println(9, "AccessLogViewer: AccessDataCommClient.finish()"); + } +} + +// Having AccessDataCommClient as an inner-class of AccessLogViewerModel causes +// compilation errors on NT when the build tree is sufficiently deep. +// for example: D:\admin\admin50\builds\20000326.1\ztNT4.0\ +class AccessLogLengthCommClient extends LogLengthCommClient +{ + AccessLogViewerModel model; + + public AccessLogLengthCommClient(AccessLogViewerModel model, String username, String password) { + super(username, password); + this.model = model; + Debug.println(9, "AccessLogViewer: AccessLogLengthCommClient."); + } + + public synchronized void finish() { + super.finish(); + model._logLengthAvailable = true; + model._logLengthCalculating = false; + model.tableDataChanged(); + Debug.println(9, "AccessLogViewer: AccessLogLengthCommClient.finish()"); + } +} diff --git a/src/com/netscape/management/admserv/logging/ErrorLogViewerModel.java b/src/com/netscape/management/admserv/logging/ErrorLogViewerModel.java new file mode 100644 index 0000000..0b0e5fd --- /dev/null +++ b/src/com/netscape/management/admserv/logging/ErrorLogViewerModel.java @@ -0,0 +1,246 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.logging; + +import java.io.*; +import java.util.*; +import java.net.*; +import javax.swing.table.*; +import com.netscape.management.client.comm.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.logging.*; +import com.netscape.management.client.util.*; +import com.netscape.management.admserv.*; + +public class ErrorLogViewerModel extends LogViewerModel { + ConsoleInfo _consoleInfo; + String _url; + String _username; + String _password; + int _logLength = 0; + private boolean _isInitialized = false; + private boolean _logLengthAvailable = false; + private boolean _logLengthCalculating = false; + StringBuffer _logLengthStringBuffer = null; + public static ResourceSet _resource = AdminServer._resource; + + public ErrorLogViewerModel(ConsoleInfo consoleInfo, String url) { + super(); + _consoleInfo = consoleInfo; + _url = _consoleInfo.getAdminURL() + url; + _username = _consoleInfo.getAuthenticationDN(); + _password = _consoleInfo.getAuthenticationPassword(); + + addColumn(_resource.getString("log", "lineno")); + addColumn(_resource.getString("log", "date")); + addColumn(_resource.getString("log", "time")); + addColumn(_resource.getString("log", "severity")); + addColumn(_resource.getString("log", "details")); + + _isInitialized = true; + } + + public void populateRows(int rowStartIndex, int numRows) { + Debug.println(6, + "ErrorLogViewer: populateRows " + rowStartIndex + + " to " + (rowStartIndex + numRows)); + try { + URL url = new URL(_url + "?op=read" + "&start=" + + rowStartIndex + "&stop=" + + (rowStartIndex + numRows) + "&" + + URLEncoder.encode("name=../../../../admin-serv/logs/error")); + HttpManager _httpManager = new HttpManager(); + ErrorLogDataClient commClient = + new ErrorLogDataClient(_username, _password); + _httpManager.get(url, commClient, (ILogViewerModel) this, + CommManager.ASYNC_RESPONSE | + CommManager.FORCE_BASIC_AUTH); + } catch (Exception e) { + Debug.println(4, "ErrorLogViewer: populateRows() " + e); + } + } + + + + /** + * Returns the number of rows in log file + */ + public int getLogLength() { + if (!_isInitialized) + return -1; + + long _currentTimeMillis = System.currentTimeMillis(); + if (((_currentTimeMillis - _lastLogLengthCheckTime) > + UPDATE_INTERVAL) && !_logLengthCalculating) { + _lastLogLengthCheckTime = _currentTimeMillis; + try // to update _logLength + { + _logLengthCalculating = true; + _logLengthAvailable = false; + _logLengthStringBuffer = new StringBuffer(); + URL url = new URL(_url + "?op=count" + "&" + + URLEncoder.encode("name=../../../../admin-serv/logs/error")); + HttpManager _httpManager = new HttpManager(); + LogLengthCommClient commClient = + new ErrorLogLengthCommClient(_username, _password); + _httpManager.get(url, commClient, _logLengthStringBuffer, + CommManager.ASYNC_RESPONSE | + CommManager.FORCE_BASIC_AUTH); + } catch (Exception e) { + _logLengthCalculating = false; + Debug.println(4, "ErrorLogViewer: getLogLength(): " + e); + } + } + + if (_logLengthAvailable) { + try { + _logLength = Integer.parseInt( + _logLengthStringBuffer.toString()); + Debug.println(6, + "ErrorLogViewer: _logLength=" + _logLength); + } catch (NumberFormatException e) { + Debug.println(4, + "ErrorLogViewer: Cannot convert log length: " + + _logLengthStringBuffer.toString()); + } + } + + return _logLength; + } + + class ErrorLogDataClient extends AbstractCommClient { + final int STATE_START = 0; + final int STATE_DATE = 1; + final int STATE_TIME = 2; + final int STATE_SEVERITY = 3; + final int STATE_DETAIL = 4; + protected LogViewerModel _model; + + public ErrorLogDataClient(String username, String password) { + super(username, password); + } + + class ErrorLogData { + StringBuffer date = new StringBuffer(); + StringBuffer time = new StringBuffer(); + StringBuffer severity = new StringBuffer(); + StringBuffer detail = new StringBuffer(); + } + + + protected ErrorLogData parse(String logEntry) { + StringBuffer buffer = new StringBuffer(logEntry); + ErrorLogData data = new ErrorLogData(); + int bufferLength = buffer.length(); + int state = STATE_START; + char character; + + for (int index = 0; index < bufferLength; index++) { + character = buffer.charAt(index); + switch (state) { + case STATE_START: + if (character == '[') + state = STATE_DATE; + break; + + case STATE_DATE: + if (character == ':') + state = STATE_TIME; + else + data.date.append(character); + break; + + case STATE_TIME: + if (character == ']') + state = STATE_SEVERITY; + else + data.time.append(character); + break; + + case STATE_SEVERITY: + if (character == ':') + state = STATE_DETAIL; + else if (character != ' ') + data.severity.append(character); + break; + + case STATE_DETAIL: + data.detail.append(character); + break; + } + } + return data; + } + + public void replyHandler(InputStream replyStream, CommRecord cr) { + BufferedReader replyBuffer = new BufferedReader( + new InputStreamReader(replyStream)); + ILogViewerModel model = (ILogViewerModel) cr.getArg(); + int rowOffset = model.getRowOffset(); + int bufferLength = model.getBufferLength(); + String logEntry = null; + for (int rowIndex = 0; rowIndex < bufferLength; rowIndex++) { + try { + logEntry = replyBuffer.readLine(); + } catch (Exception e) { + Debug.println(4, + "ErrorLogViewer: repxlyHandler() " + e); + } + if (logEntry != null) { + ErrorLogData d = parse(logEntry); + model.setValueAt( + Integer.toString(rowOffset + rowIndex), + rowIndex, 0); + model.setValueAt(d.date, rowIndex, 1); + model.setValueAt(d.time, rowIndex, 2); + model.setValueAt(d.severity, rowIndex, 3); + model.setValueAt(d.detail, rowIndex, 4); + } else { + break; + } + } + finish(); + } + + + public synchronized void finish() { + super.finish(); + ErrorLogViewerModel.this.tableDataChanged(); + } + } + + public class ErrorLogLengthCommClient extends LogLengthCommClient { + public ErrorLogLengthCommClient(String username, String password) { + super(username, password); + Debug.println(9, "ErrorLogViewer: ErrorLogLengthCommClient."); + } + + public synchronized void finish() { + super.finish(); + _logLengthAvailable = true; + _logLengthCalculating = false; + ErrorLogViewerModel.this.tableDataChanged(); + Debug.println(9, "ErrorLogViewer: ErrorLogLengthCommClient.finish()"); + } + } +} + + diff --git a/src/com/netscape/management/admserv/panel/AccessConfigPanel.java b/src/com/netscape/management/admserv/panel/AccessConfigPanel.java new file mode 100644 index 0000000..0a62057 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/AccessConfigPanel.java @@ -0,0 +1,251 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.awt.*; +import javax.swing.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.nmclf.SuiConstants; + +/** + * + * @version 0.1 11/23/97 + * @author miodrag@netscape.com + */ +public class AccessConfigPanel extends PluginConfigPanel implements SuiConstants { + + IConfigDataModel _configData; + + static ResourceSet _resource; + static String _i18nUID, _i18nPWD, _i18nConfirmPWD; + static String _i18nAdmSuperuser, _i18nAllowDSGW; + static String _i18nMsgEnterUID, _i18nMsgEnterPWD, _i18nMsgPWDMismatch; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nAdmSuperuser = _resource.getString("access","AdmSuperuser"); + _i18nUID = _resource.getString("access","UID"); + _i18nPWD = _resource.getString("access","PWD"); + _i18nConfirmPWD = _resource.getString("access","ConfirmPWD"); + _i18nAllowDSGW = _resource.getString("access","AllowDSGW"); + _i18nMsgEnterUID = _resource.getString("access","MsgEnterUID"); + _i18nMsgEnterPWD = _resource.getString("access","MsgEnterPWD"); + _i18nMsgPWDMismatch = _resource.getString("access","MsgPWDMismatch"); + } + + Help _help; + + JCheckBox _cbDSGW; + SingleByteTextField _txtUserName; + SingleBytePasswordField _txtPassword, _txtConfirm; + + + public AccessConfigPanel(String title, IConfigDataModel data) { + super(title); + _configData = data; + + setLayout(new BorderLayout()); + add(makeConfigPanel(), BorderLayout.NORTH); + _help = new Help(_resource); + } + + + public void showHelp() { + _help.contextHelp("accessHelp"); + } + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) { + _configData = data; + if (_configData.isLoaded()) { + setPanelContent(_configData); + } + } + + public void initialize() throws RemoteRequestException { + if (!_configData.isLoaded()) + _configData.load(); + setPanelContent(_configData); + } + + public void resetContent() { + setPanelContent(_configData); + } + + public void applyChanges() throws ValidationException { + try { + getPanelContent(_configData); + } catch (ValidationException e) { + throw e; + } + } + + public void registerEditComponents(EditMonitor editMonitor) { + editMonitor.monitor(_txtUserName); + editMonitor.monitor(_txtPassword); + editMonitor.monitor(_txtConfirm); + //editMonitor.monitor(_cbDSGW); + } + + public void setPanelContent(IConfigDataModel data) { + //String dsgw = data.getAttribute(AttrNames.CONFIG_DSGW); + //setDSGW(!dsgw.equalsIgnoreCase("off")); + + setUserName(data.getAttribute(AttrNames.ADMPW_UID)); + _txtPassword.setText(""); + _txtConfirm.setText(""); + } + + public void getPanelContent(IConfigDataModel data) + throws ValidationException { + + //String dsgw = (_cbDSGW.isSelected()) ? "on" : "off"; + //data.setAttribute(AttrNames.CONFIG_DSGW, dsgw); + + String newuid = _txtUserName.getText(); + String newpw1 = _txtPassword.getText(); + String newpw2 = _txtConfirm.getText(); + String olduid = _configData.getAttribute(AttrNames.ADMPW_UID); + + if (newuid.length() == 0) { + throw new ValidationException("", _i18nMsgEnterUID); + } + // User name changed + else if (!olduid.equals(newuid)) { + if (newpw1.length() == 0) { + throw new ValidationException("", _i18nMsgEnterPWD); + } else if (!newpw1.equals(newpw2)) { + throw new ValidationException("", _i18nMsgPWDMismatch); + } + } else { // check if password changed + if (newpw1.length() != 0) { + if (!newpw1.equals(newpw2)) { + throw new ValidationException("", _i18nMsgPWDMismatch); + } + } + } + + if (! newuid.equals(olduid)) { + Debug.println("CHANGE UID TO " + newuid); + _configData.setAttribute(AttrNames.ADMPW_UID, newuid); + } + if (newpw1.length() > 0) { + Debug.println("CHANGE PWD "); + _configData.setAttribute(AttrNames.ADMPW_PWD, newpw1); + } + + } + + private void setUserName(String name) { + _txtUserName.setText((name == null) ? "" : name); + } + + + void setDSGW(boolean flag) { + _cbDSGW.setSelected(flag); + } + + private JPanel makeConfigPanel() { + + JPanel p = new JPanel(); + GBC gbc = new GBC(); + GridBagLayout gbl; + JPanel ctrlGroup; + + p.setLayout(gbl = new GridBagLayout()); + + //gbc.setInsets(0,leftColInset,0,0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(createSuperuserGroup(), gbc); + + _cbDSGW = new JCheckBox(_i18nAllowDSGW, true); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 2, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.NONE); //fill + + //p.add(_cbDSGW, gbc); + + return p; + } + + private JPanel createSuperuserGroup() { + GridBagLayout gbl; + GBC gbc = new GBC(); + JPanel group = new JPanel(gbl = new GridBagLayout()); + group.setBorder( + BaseConfigPanel.createGroupBorder(_i18nAdmSuperuser)); + + JLabel uidLabel = new JLabel(_i18nUID); + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, //anchor + GBC.NONE); //fill + group.add(uidLabel, gbc); + + _txtUserName = new SingleByteTextField(16); + gbc.setInsets(0, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(_txtUserName, gbc); + uidLabel.setLabelFor(_txtUserName); + + JLabel pwdLabel = new JLabel(_i18nPWD); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, //anchor + GBC.NONE); //fill + group.add(pwdLabel, gbc); + + _txtPassword = new SingleBytePasswordField(16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(_txtPassword, gbc); + pwdLabel.setLabelFor(_txtPassword); + + JLabel pwd2Label = new JLabel(_i18nConfirmPWD); + gbc.setInsets(DIFFERENT_COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 2, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, //anchor + GBC.NONE); //fill + group.add(pwd2Label, gbc); + + _txtConfirm = new SingleBytePasswordField(16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 2, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(_txtConfirm, gbc); + pwd2Label.setLabelFor(_txtConfirm); + + return group; + } +} diff --git a/src/com/netscape/management/admserv/panel/AdminConfigData.java b/src/com/netscape/management/admserv/panel/AdminConfigData.java new file mode 100644 index 0000000..84a545b --- /dev/null +++ b/src/com/netscape/management/admserv/panel/AdminConfigData.java @@ -0,0 +1,63 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class AdminConfigData extends CGIAggregateDataModel { + public AdminConfigData(ConsoleInfo consoleInfo) { + super(consoleInfo); + } + + /** + * Check if the server is NT platform + */ + static public boolean isWindowsNTPlatform(ConsoleInfo ci) { + String platform = (String) ci.getAdminOS(); + return (platform != null && platform.startsWith("Win")); + } + + static public boolean isRunning(String adminURL) { + try { + URL serverURL = new URL(adminURL); + URLConnection server = serverURL.openConnection(); + server.connect(); + return true; + } catch (MalformedURLException ex) { + Debug.println("ERROR AdminConfigData.isRunning: bad URL " + + adminURL); + } + catch (java.io.IOException ex) { + Debug.println("AdminConfigData.isRunning: " + ex); + } + + return false; + } +} diff --git a/src/com/netscape/management/admserv/panel/AdminConfigPanel.java b/src/com/netscape/management/admserv/panel/AdminConfigPanel.java new file mode 100644 index 0000000..c4295c3 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/AdminConfigPanel.java @@ -0,0 +1,146 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.awt.*; +import javax.swing.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.admserv.*; + + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class AdminConfigPanel extends TabbedConfigPanel { + static ResourceSet _resource; + static String _i18nNetworkTab, _i18nAccessTab, + _i18nConfigDirectoryTab, _i18nUGDirectoryTab, _i18nEncryptionTab; + ConsoleInfo _consoleInfo; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nNetworkTab = _resource.getString("config","NetworkTab"); + _i18nAccessTab = _resource.getString("config","AccessTab"); + _i18nConfigDirectoryTab = _resource.getString("config","ConfigDirectoryTab"); + _i18nUGDirectoryTab = _resource.getString("config","UGDirectoryTab"); + _i18nEncryptionTab = _resource.getString("config","EncryptionTab"); + } + + + IConfigDataModel _configData; + NetworkConfigPanel _networkTab; + TurnOnSSL _encryptionTab; + AccessConfigPanel _accessTab; + DirectoryConfigPanel _configDirectoryTab; + UGDirectoryConfigPanel _ugDirectoryTab; + int _accessIdx = -1, _encryptionIdx = -1, _configDirectoryIdx = -1, + _UGDirectoryIdx = -1; + ; + boolean _unixServer; + + public AdminConfigPanel(ConsoleInfo consoleInfo) { + super(LAZY_CREATE); + + this._consoleInfo = consoleInfo; + + _unixServer = ! AdminConfigData.isWindowsNTPlatform(consoleInfo); + _configData = new AdminConfigData(consoleInfo); + addTabPanes(); + } + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) + throws ConfigPanelException { + super.setDataModel(_configData = data); + } + + protected void addTabPanes() { + + addDataModel(AttrNames.CONFIG_CGI_PREFIX, + new CGIServerSetup(_consoleInfo)); + addTab(_i18nNetworkTab, null, + _networkTab = + new NetworkConfigPanel("", _configData, _unixServer)); + + _accessIdx = lazyModeReserveTab(_i18nAccessTab, null); + + if (AdminFrameworkInitializer.canAccessSecurity) { + _encryptionIdx = lazyModeReserveTab(_i18nEncryptionTab, null); + } + + _configDirectoryIdx = + lazyModeReserveTab(_i18nConfigDirectoryTab, null); + _UGDirectoryIdx = lazyModeReserveTab(_i18nUGDirectoryTab, null); + } + + public IPluginConfigPanel lazyModeCreateTab(int idx) { + if (idx == _accessIdx) { + addDataModel(AttrNames.ADMPW_CGI_PREFIX, + new CGIAccessSetup(_consoleInfo)); + return _accessTab = new AccessConfigPanel("", _configData); + } + else if (idx == _encryptionIdx) { + return _encryptionTab = new TurnOnSSL(_consoleInfo); + } + else if (idx == _configDirectoryIdx) { + addDataModel(AttrNames.DSCONFIG_CGI_PREFIX, + new CGIDirectorySetup(_consoleInfo)); + return _configDirectoryTab = + new DirectoryConfigPanel("", _configData); + } + else if (idx == _UGDirectoryIdx) { + addDataModel(AttrNames.UGDSCONFIG_CGI_PREFIX, + new CGIUGDirectorySetup(_consoleInfo)); + return _ugDirectoryTab = + new UGDirectoryConfigPanel("", _configData); + } + else { + throw new Error("Bad tab idx " + idx); + } + } + + private void addDataModel(String prefix, CGIDataModel cgi) { + AdminConfigData aggrModel; + + aggrModel = (AdminConfigData)_configData; + aggrModel.add(prefix, cgi); + } + + public void initialize() throws ConfigPanelException { + + try { + if (!_configData.isLoaded()) { + _configData.load(); + } + super.initialize(); // initialize all + } catch (ConfigPanelException e) { + throw e; + } + } +} + diff --git a/src/com/netscape/management/admserv/panel/AdminOperation.java b/src/com/netscape/management/admserv/panel/AdminOperation.java new file mode 100644 index 0000000..c2e149b --- /dev/null +++ b/src/com/netscape/management/admserv/panel/AdminOperation.java @@ -0,0 +1,332 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.lang.reflect.Method; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import java.util.*; +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.admserv.panel.IRestartControl; +import com.netscape.management.nmclf.SuiLookAndFeel; +import javax.swing.border.EmptyBorder; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class AdminOperation { + static ResourceSet _resource; + static String _i18nStatus, _i18nFailureStatus, _i18nWarningStatus, + _i18nCanNotConnect, _i18nServerShutdown; + static String _i18nOperationDone, _i18nOperationFailed; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nStatus = _resource.getString("adminop","Status"); + _i18nFailureStatus = _resource.getString("adminop","FailureStatus"); + _i18nWarningStatus = _resource.getString("adminop","WarningStatus"); + _i18nCanNotConnect = _resource.getString("adminop","CanNotConnect"); + _i18nServerShutdown = _resource.getString("adminop","ServerShutdown"); + _i18nOperationDone = _resource.getString("adminop","OperationDone"); + _i18nOperationFailed = _resource.getString("adminop","OperationFailed"); + } + + + protected ConsoleInfo _consoleInfo; + protected boolean _actionPerformed; + protected Hashtable _resultData; + protected int _resultStatus; + protected String _taskURL; + protected IAdminOperationListener _listener; + + protected ActionMonitorPanel _actionPanel; + protected AdmTask _task; + + public AdminOperation(ConsoleInfo consoleInfo, String taskURL) { + _consoleInfo = consoleInfo; + _taskURL = taskURL; + } + + public JPanel getPanel() { + return _actionPanel; + } + + public Hashtable getConsoleInfo() { + return _consoleInfo; + } + + /** + * Close dialog if base config panel is running inside a dialog + */ + public Dialog getDialog() { + Component c = _actionPanel; + Dialog dialog = null; + while ((c = c.getParent()) != null) { + if (c instanceof Dialog) { + dialog = (Dialog) c; + break; + } + } + return dialog; + } + + public Frame getFrame() { + Component c = _actionPanel; + Frame frame = null; + while ((c = c.getParent()) != null) { + if (c instanceof Frame) { + frame = (Frame) c; + break; + } + } + return frame; + } + + protected void closeDialog() { + Window dialog = getDialog(); + + if (dialog != null) { + dialog.setVisible(false); + dialog.dispose(); + ModalDialogUtil.sleep(); + } + } + + + protected void createActionPanel(boolean multilined) { + _actionPanel = new ActionMonitorPanel(multilined); + //_actionPanel.setBorder(new EmptyBorder(0, SuiLookAndFeel.HORIZ_WINDOW_INSET, + //SuiLookAndFeel.VERT_WINDOW_INSET, SuiLookAndFeel.HORIZ_WINDOW_INSET)); + } + + + /** + * Monitor execution of the operatinal task + */ + public void monitorOperation(String description) { + monitorOperation(description, null); + } + + + public void monitorOperation(String description, + IAdminOperationListener listener) { + + if (ActionMonitorPanel.getActiveInstance() != null) { + _actionPanel = ActionMonitorPanel.getActiveInstance(); + _actionPanel.setStatusText(description); + try { + AdminOperation.this.performOperation(listener); + } catch (RemoteRequestException e) { + ConfigErrorDialog.showDialog(_actionPanel, e); + } + return; + } + + if (_actionPanel == null) { + createActionPanel(false); + } + + + // Granting UniversalThreadGroupAccess before creating thread groups + //(as instructed by DT) + + Method m = Permissions.getEnablePrivilegeMethod(); + if (m != null) { + Object[] args = new Object[1]; + args[0] = "UniversalThreadGroupAccess"; + + try { + m.invoke(null, args); + } catch (Exception e) { + Debug.println( + "AdminOperation:monitorOperation():unable to grant ThreadGroup privileges:" + e); + } + } + + final ThreadGroup tg = new ThreadGroup("LongActionTG"); + final String status = description; + final IAdminOperationListener listenerObject = listener; + Thread t = new Thread(tg, "LongAction") { + public void run() { + // Give dialog time to popup + //try { Thread.currentThread().sleep(200); } catch (Exception e) {} + boolean noError = true; + _actionPanel.monitorProgressStart(status, tg, + _stopAction); + try { + AdminOperation.this.performOperation( + listenerObject); + } catch (RemoteRequestException e) { + ConfigErrorDialog.showDialog(_actionPanel, e); + noError = false; + } + finally { if (noError && + _actionPanel.isMultilined()) { + _actionPanel.monitorProgressWaitForClose(); + return; + } + _actionPanel.monitorProgressStop( + _actionPerformed ? _i18nOperationDone : + _i18nOperationFailed); + // Some time to read status + try { + Thread.currentThread().sleep(500); + } catch (Exception e) {} + closeDialog(); + } } + + ActionListener _stopAction = new ActionListener() { + public void actionPerformed( + ActionEvent e) { + closeDialog(); + } + }; + + }; + t.start(); + } + + public void performOperation(IAdminOperationListener listener) + throws RemoteRequestException { + try { + performOperationalTask(_consoleInfo, _taskURL); + if (listener != null) { + listener.cgiRequestCompleted(_consoleInfo); + } + } catch (RemoteRequestException e) { + throw e; + } + } + + + protected void createTask(ConsoleInfo ci, + String adminURL) throws RemoteRequestException { + + try { + _task = new AdmTask(new URL(adminURL), ci.getAuthenticationDN(), + ci.getAuthenticationPassword()); + } catch (MalformedURLException e) { + Debug.println(""+e); + throw new RemoteRequestException(e); + } + } + + public void performOperationalTask(ConsoleInfo ci, + String taskURL) throws RemoteRequestException { + + + String adminURL = ci.getAdminURL() + taskURL; + createTask(ci, adminURL); + + //_task.trace(); + _task.exec(); + + _resultStatus = _task.getStatus(); + _resultData = _task.getResult(); + _actionPerformed = (_resultStatus == 0 || _resultStatus == 3); + processAdmTaskStatus(adminURL); + } + + public boolean isActionPerformed() { + return _actionPerformed; + } + + public int getResultStatus() { + return _resultStatus; + } + + public Hashtable getResultData() { + return _resultData; + } + + + // Need this as static methods can not be overriden + protected void processAdmTaskStatus(String url) + throws RemoteRequestException { + processAdmTaskStatus(url, _task, _consoleInfo); + } + + public static void processAdmTaskStatus(String url, AdmTask task, + ConsoleInfo ci) throws RemoteRequestException { + + int status = task.getStatus(); + + if (status == 0 || status == 3) { + return; + } + else if (status < 0) { // -1 if HTTP Exception received + Debug.println("HTTP Exception status=" + status + " " + + task.getException()); + if (task.getException() != null && task.getException() + instanceof java.net.SocketException) { + IRestartControl serverStatus = + (IRestartControl) ci.get(IRestartControl.ID); + if (serverStatus != null) { + if (serverStatus.isServerShutdown()) { + throw new RemoteRequestException("", + _i18nServerShutdown); + } + } else { + Debug.println("StopOperation: restart activator not in ConsoleInfo"); + } + + // Server is not shutdown, throw can not connect + throw new RemoteRequestException(url, + _i18nCanNotConnect + " "+ + task.getException().getMessage()); + + } + else if (task.getException() != null) { + throw new RemoteRequestException(task.getException()); + } else { + throw new RemoteRequestException(url, _i18nStatus + status); + } + } + else { // (status > 0) an error generated by the CGI script + String type; + if (status == 1) + type = _i18nStatus + _i18nFailureStatus; + else if (status == 2) + type = _i18nStatus + _i18nWarningStatus; + else + type = _i18nStatus + " " + status; + + String msg = ""; + Hashtable result = task.getResult(); + if (result != null) { + for (Enumeration e = result.elements(); + e.hasMoreElements();) { + Object key = e.nextElement(); + //msg=msg + key + "=" + result.get(key) + "\n"; + msg = msg + key + "\n"; + } + } + Debug.println("CGI error " + type + "\n" + msg); + throw new RemoteRequestException(url, type + "\n" + msg); + } + } +} diff --git a/src/com/netscape/management/admserv/panel/AttrNames.java b/src/com/netscape/management/admserv/panel/AttrNames.java new file mode 100644 index 0000000..5ea24dc --- /dev/null +++ b/src/com/netscape/management/admserv/panel/AttrNames.java @@ -0,0 +1,60 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +public class AttrNames { + + public static final String CONFIG_CGI_PREFIX = "configuration"; + public static final String CONFIG_SERVERPORT = "configuration.nsserverport"; + public static final String CONFIG_SERVERADDRESS = "configuration.nsserveraddress"; + public static final String CONFIG_HOSTS = "configuration.nsadminaccesshosts"; + public static final String CONFIG_ADDRESSES = "configuration.nsadminaccessaddresses"; + public static final String CONFIG_USER = "configuration.nssuitespotuser"; + public static final String CONFIG_ACCESSLOG = "configuration.nsaccesslog"; + public static final String CONFIG_ERRORLOG = "configuration.nserrorlog"; + public static final String CONFIG_DSGW = "configuration.nsadminenabledsgw"; + public static final String CONFIG_ENDUSER = "configuration.nsadminenableenduser"; + + public static final String ADMPW_CGI_PREFIX = "admpw"; + public static final String ADMPW_UID = "admpw.uid"; + public static final String ADMPW_PWD = "admpw.pw"; + + public static final String DSCONFIG_CGI_PREFIX = "dsconfig"; + public static final String DSCONFIG_HOST = "dsconfig.host"; + public static final String DSCONFIG_PORT = "dsconfig.port"; + public static final String DSCONFIG_BASEDN = "dsconfig.basedn"; + public static final String DSCONFIG_SSL = "dsconfig.ssl"; + + public static final String UGDSCONFIG_CGI_PREFIX = "ugdsconfig"; + public static final String UGDSCONFIG_INFOREF = "ugdsconfig.inforef"; + public static final String UGDSCONFIG_GLOBALDIRURL = "ugdsconfig.globaldirurl"; + public static final String UGDSCONFIG_DIRURL = "ugdsconfig.dirurl"; + public static final String UGDSCONFIG_BINDDN = "ugdsconfig.binddn"; + public static final String UGDSCONFIG_BINDPW = "ugdsconfig.bindpw"; + public static final String UGDSCONFIG_HOST = "ugdsconfig.host"; + public static final String UGDSCONFIG_PORT = "ugdsconfig.port"; + public static final String UGDSCONFIG_BASEDN = "ugdsconfig.basedn"; + public static final String UGDSCONFIG_SSL = "ugdsconfig.ssl"; + + public static final String SNMP_CGI_PREFIX = "snmp"; + public static final String SNMP_COMMUNITIES = "snmp.communities"; + public static final String SNMP_MANAGERS = "snmp.managers"; +} diff --git a/src/com/netscape/management/admserv/panel/CGIAccessSetup.java b/src/com/netscape/management/admserv/panel/CGIAccessSetup.java new file mode 100644 index 0000000..1d3bf55 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/CGIAccessSetup.java @@ -0,0 +1,91 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class CGIAccessSetup extends CGIDataModel { + private static String _taskURL = "admin-serv/tasks/Configuration/AccessSetup"; + + private boolean _dsgwAdded = false; + + public CGIAccessSetup(ConsoleInfo consoleInfo) { + super(consoleInfo, _taskURL); + } + + /** + * CGI arguments used in getConfiguration() + */ + public String getCGIParamsForGetOp() { + return "op=get"; + } + + /** + * CGI arguments used in setConfiguration() + */ + public String getCGIParamsForSetOp() { + String uid = getAttribute(AttrNames.ADMPW_UID); + return "op=set&" + AttrNames.ADMPW_UID + "=" + + URLByteEncoder.encodeUTF8(uid); + + } + + public void save() throws RemoteRequestException { + + super.save(); + + // Use change-sie-passwod command to change the password + String pwd = getAttribute(AttrNames.ADMPW_PWD); + + if (pwd != null) { + AdmTask task = null; + String _taskURL = "admin-serv/commands/change-sie-password"; + String adminURL = _consoleInfo.getAdminURL() + _taskURL; + adminURL = adminURL + "?" + URLByteEncoder.encodeUTF8(pwd); + try { + task = new AdmTask(new URL(adminURL), + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + } catch (MalformedURLException e) { + Debug.println("CGIDataModel.setConfiguration "+e); + throw new RemoteRequestException(e); + } + + task.exec(); + + int status = task.getStatus(); + Debug.println(adminURL + " "+status); + AdminOperation.processAdmTaskStatus(adminURL, task, + _consoleInfo); + } + } + + +} diff --git a/src/com/netscape/management/admserv/panel/CGIAggregateDataModel.java b/src/com/netscape/management/admserv/panel/CGIAggregateDataModel.java new file mode 100644 index 0000000..add1f73 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/CGIAggregateDataModel.java @@ -0,0 +1,201 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.panel.*; + +/** + * + * @version 0.1 01/15/98 + * @author miodrag@netscape.com + */ + + +/** + * A config data model that is an aggregate of multiple cgi data models. + * It is intended for panels that need to work with multiple CGIs. + */ +public class CGIAggregateDataModel implements IConfigDataModel { + private static String _clazz = "CGIAggregateDataModel"; + protected Hashtable _CGIs; + protected String _modelName; + protected ConsoleInfo _consoleInfo; + + public CGIAggregateDataModel(ConsoleInfo consoleInfo) { + _CGIs = new Hashtable(); + _consoleInfo = consoleInfo; + } + + public void add(String prefix, CGIDataModel cgi) { + _CGIs.put(prefix, cgi); + } + + public void remove(String prefix) { + _CGIs.remove(prefix); + } + + + public void setDialogParent (java.awt.Component comp) { + for (Enumeration e = _CGIs.elements(); e.hasMoreElements();) { + CGIDataModel cgi = (CGIDataModel) e.nextElement(); + cgi.setDialogParent(comp); + } + } + + public IConfigDataModel getCGI(String prefix) { + return (IConfigDataModel)_CGIs.get(prefix); + } + + protected String getAttrPrefix (String attrName) { + int dot = attrName.indexOf('.'); + if (dot > 0) { + return attrName.substring(0, dot); + } else { + Debug.println("dot not found in " + attrName); + return null; + } + } + + public String getAttribute(String attr) { + //Debug.println("ATTR=" + attr + " PREFIX=" + getAttrPrefix(attr)); + IConfigDataModel cgi = + (IConfigDataModel)_CGIs.get(getAttrPrefix(attr)); + if (cgi != null) { + return cgi.getAttribute(attr); + } else { + Debug.println(_clazz + + ".getAttribute() CGI for the attr " + attr + " not in data model"); + return ""; + } + } + + public void setAttribute(String attr, + String val) throws ValidationException { + IConfigDataModel cgi = + (IConfigDataModel)_CGIs.get(getAttrPrefix(attr)); + if (cgi != null) { + cgi.setAttribute(attr, val); + } else { + Debug.println(_clazz + + ".setAttribute() CGI for the attr " + attr + " not in data model"); + } + } + + public Enumeration getAttributes() { + // to do implement AggregateEnumerator + return new CGIAggregateEnumerator(_CGIs); + } + + public boolean isLoaded() { + for (Enumeration e = _CGIs.elements(); e.hasMoreElements();) { + IConfigDataModel cgi = (IConfigDataModel) e.nextElement(); + if (!cgi.isLoaded()) { + return false; + } + } + return true; + } + + public boolean isModified() { + for (Enumeration e = _CGIs.elements(); e.hasMoreElements();) { + IConfigDataModel cgi = (IConfigDataModel) e.nextElement(); + if (cgi.isModified()) { + return true; + } + } + return false; + } + + + /** + * Load all CGIs + */ + public void load() throws RemoteRequestException { + for (Enumeration e = _CGIs.elements(); e.hasMoreElements();) { + IConfigDataModel cgi = (IConfigDataModel) e.nextElement(); + if (!cgi.isLoaded()) { + cgi.load(); + } + } + } + + /** + * Save all modified CGIs + */ + public void save() throws RemoteRequestException { + for (Enumeration e = _CGIs.elements(); e.hasMoreElements();) { + IConfigDataModel cgi = (IConfigDataModel) e.nextElement(); + if (cgi.isModified()) { + cgi.save(); + } + } + } + + public String getModelName() { + return CGIDataModel.getServerName(_consoleInfo); + } + + public ConsoleInfo getConsoleInfo() { + return _consoleInfo; + } + +} + + +/** + * An enumerator class for a hashtable of CGIDataModels + */ +class CGIAggregateEnumerator implements Enumeration { + + Hashtable _aggregateTable; + Enumeration _aggregateEnum; + Enumeration _curEnum; + + CGIAggregateEnumerator(Hashtable aggregateTable) { + _aggregateTable = aggregateTable; + _aggregateEnum = _aggregateTable.elements(); + } + + public boolean hasMoreElements() { + if (_curEnum == null || !_curEnum.hasMoreElements()) { + if (!_aggregateEnum.hasMoreElements()) { + _curEnum = null; + return false; + } + CGIDataModel curTable = + (CGIDataModel)_aggregateEnum.nextElement(); + _curEnum = curTable.getAttributes(); + } + return _curEnum.hasMoreElements(); + } + + public Object nextElement() { + if (_curEnum == null) { + throw new NoSuchElementException("AggregateHashtableEnumerator"); + } + return _curEnum.nextElement(); + } +} diff --git a/src/com/netscape/management/admserv/panel/CGIDataModel.java b/src/com/netscape/management/admserv/panel/CGIDataModel.java new file mode 100644 index 0000000..7aa9a98 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/CGIDataModel.java @@ -0,0 +1,297 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.net.*; +import java.text.MessageFormat; +import com.netscape.management.client.util.*; +import com.netscape.management.client.comm.HttpChannel; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public abstract class CGIDataModel implements IConfigDataModel { + + static ResourceSet _resource; + static String _i18nProgressLoading, _i18nProgressSaving, + _i18nLoadFailed, _i18nSaveFailed; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nProgressLoading = _resource.getString("adminop","ProgressLoading"); + _i18nProgressSaving = _resource.getString("adminop","ProgressSaving"); + _i18nLoadFailed = _resource.getString("adminop","LoadFailed"); + _i18nSaveFailed = _resource.getString("adminop","SaveFailed"); + } + + protected Hashtable _data, _origData; + protected ConsoleInfo _consoleInfo; + protected boolean _loaded, _saved, _modified; + protected String _taskURL; + protected String _adminURL; + + protected java.awt.Component _dialogParent; // for info messages + + public CGIDataModel(ConsoleInfo consoleInfo, String taskURL) { + _consoleInfo = consoleInfo; + _taskURL = taskURL; + _adminURL = _consoleInfo.getAdminURL() + _taskURL; + } + + static public String getServerName(ConsoleInfo ci) { + String server = (String) ci.get("SERVER_NAME"); + if (server == null) { + Debug.println("CGIDataModel.getServerName: SERVER_NAME not found in console info"); + return "unknown"; + } + return server; + } + + public String getModelName() { + return getServerName(_consoleInfo); + } + + + public ConsoleInfo getConsoleInfo() { + return _consoleInfo; + } + + public Enumeration getAttributes() { + return _data.keys(); + } + + /** + * Implements IConfigDataModel.isLoaded() + */ + public boolean isLoaded() { + return _loaded; + } + + /** + * Implements IConfigDataModel.load() + */ + public void load() throws RemoteRequestException { + if (ActionMonitorPanel.getActiveInstance() != null) { + MessageFormat msg = new MessageFormat(_i18nProgressLoading); + Object[] msgArgs = { "" }; //{ getModelName() }; + ActionMonitorPanel.getActiveInstance().setStatusText( + msg.format(msgArgs)); + } + _data = getConfiguration(_adminURL, getCGIParamsForGetOp()); + _loaded = ! _data.isEmpty(); + if (!_loaded) { + throw new RemoteRequestException(_adminURL, _i18nLoadFailed); + } + _origData = cloneStringHashtable(_data, null); + } + + /** + * Implements IConfigDataModel.isLoaded() + */ + public boolean isModified() { + //Debug.println(getClass().getName() + " modified=" + _modified); + return _modified; + } + + + /** + * Implements IConfigDataModel.save() + */ + public void save() throws RemoteRequestException { + if (ActionMonitorPanel.getActiveInstance() != null) { + MessageFormat msg = new MessageFormat(_i18nProgressSaving); + Object[] msgArgs = { getModelName()}; + ActionMonitorPanel.getActiveInstance().setStatusText( + msg.format(msgArgs)); + } + + try { + setConfiguration(_adminURL, getCGIParamsForSetOp()); + if (!_saved) { + throw new RemoteRequestException(_adminURL, + _i18nSaveFailed); + } + } catch (RemoteRequestException e) { + _data.clear(); + _data = cloneStringHashtable(_origData, null); + throw e; + } + _origData.clear(); + _origData = cloneStringHashtable(_data, null); + _modified = false; + } + + /** + * Implements IConfigDataModel.getAttribute() + */ + public String getAttribute(String attr) { + return (String)_data.get(attr); + } + + /** + * Implements IConfigDataModel.setAttribute() + */ + + public void setAttribute(String attr, + String val) throws ValidationException { + String curVal = getAttribute(attr); + if (!_modified) { + _modified = (val == null) ? (curVal != null) : + !(val.equals(curVal)); + } + //Debug.println(attr + " curVal="+curVal+" val="+val+"modified="+_modified); + _data.put(attr, val); + } + + + public String toURLformat(Hashtable args) { + String p = ""; + Enumeration e = args.keys(); + while (e.hasMoreElements()) { + String name = (String) e.nextElement(); + String value = (String) args.get(name); + + p += name + "=" + URLByteEncoder.encodeUTF8(value) + + (e.hasMoreElements() ? "&":""); + } + return p; + } + + public static Hashtable cloneStringHashtable(Hashtable tbl, + String renamePrefix) { + Hashtable out = new Hashtable(); + for (Enumeration e = tbl.keys(); e.hasMoreElements();) { + String key = (String) e.nextElement(); + String val = (String) tbl.get(key); + + if (renamePrefix == null) { + out.put(new String(key), new String(val)); + } else { + out.put(renamePrefix + key, new String(val)); + } + } + return out; + } + + + public static Vector commaStringToVector(String s) { + Vector v = new Vector(); + if (s != null) { + StringTokenizer st = new StringTokenizer(s, ","); + while (st.hasMoreTokens()) { + v.addElement(st.nextToken()); + } + } + return v; + } + + public static String vectorToCommaString(Vector v) { + String s = ""; + Enumeration e = v.elements(); + while (e.hasMoreElements()) { + s = s + e.nextElement(); + if (e.hasMoreElements()) + s = s + ","; + } + return s; + } + + public java.awt.Component getDialogParent() { + return _dialogParent; + } + + public void setDialogParent (java.awt.Component comp) { + _dialogParent = comp; + } + + /** + * CGI arguments used in getConfiguration() + */ + public abstract String getCGIParamsForGetOp(); + + /** + * CGI arguments used in setConfiguration() + */ + public abstract String getCGIParamsForSetOp(); + + protected Hashtable getConfiguration(String adminURL, + String args) throws RemoteRequestException { + AdmTask task = null; + try { + task = new AdmTask(new URL(adminURL), + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + } catch (MalformedURLException e) { + Debug.println("CGIDataModel.getConfiguration "+e); + throw new RemoteRequestException(e); + } + + //task.trace(); + if (args != null) { + //task.setArguments(HttpChannel._encode(args)); + task.setArguments(args); + } + task.exec(); + + int status = task.getStatus(); + _loaded = (status == 0); + Debug.println(adminURL + " "+status); + + AdminOperation.processAdmTaskStatus(adminURL, task, _consoleInfo); + + if (task != null) { + //Debug.printHashtable("config", task.getResult()); + return task.getResult(); + } + + return new Hashtable(); + + } + + protected void setConfiguration(String adminURL, + String args) throws RemoteRequestException { + AdmTask task = null; + try { + task = new AdmTask(new URL(adminURL), + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + } catch (MalformedURLException e) { + Debug.println("CGIDataModel.setConfiguration "+e); + throw new RemoteRequestException(e); + } + + //task.trace(); + if (args != null) { + task.setArguments(args); + } + task.exec(); + + int status = task.getStatus(); + Debug.println(adminURL + " "+status); + _saved = (status == 0); + AdminOperation.processAdmTaskStatus(adminURL, task, _consoleInfo); + } +} diff --git a/src/com/netscape/management/admserv/panel/CGIDirectorySetup.java b/src/com/netscape/management/admserv/panel/CGIDirectorySetup.java new file mode 100644 index 0000000..20753c4 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/CGIDirectorySetup.java @@ -0,0 +1,71 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class CGIDirectorySetup extends CGIDataModel { + private static String _taskURL = "admin-serv/tasks/Configuration/DirectorySetup"; + + public CGIDirectorySetup(ConsoleInfo consoleInfo) { + super(consoleInfo, _taskURL); + } + + /** + * CGI arguments used in getConfiguration() + */ + public String getCGIParamsForGetOp() { + return "op=getconfig"; + } + + /** + * CGI arguments used in setConfiguration() + */ + + public String getCGIParamsForSetOp() { + String sie = (String)_consoleInfo.get("SIE"); + return "op=setconfig&" + toURLformat(_data) + + "&dsconfig.alias=" + URLByteEncoder.encodeUTF8(sie); + } + + public void save() throws RemoteRequestException { + + super.save(); + + ResourceSet resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + String msg1 = resource.getString("adminop", "ldapds-Changed"); + String msg2 = resource.getString("adminop", "ldapds-ChangedInfo"); + String title = resource.getString("adminop", "ldapds-DSGroupbox"); + ConfigInfoDialog.showDialog(getDialogParent(), + msg1 + "\n\n" + msg2, title); + } + + +} diff --git a/src/com/netscape/management/admserv/panel/CGILoggingSetup.java b/src/com/netscape/management/admserv/panel/CGILoggingSetup.java new file mode 100644 index 0000000..2eb86c2 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/CGILoggingSetup.java @@ -0,0 +1,61 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.util.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class CGILoggingSetup extends CGIDataModel { + private static String _taskURL = "admin-serv/tasks/Configuration/ServerSetup"; + + public CGILoggingSetup(ConsoleInfo consoleInfo) { + super(consoleInfo, _taskURL); + } + + /** + * CGI arguments used in getConfiguration() + */ + public String getCGIParamsForGetOp() { + return "op=get&" + AttrNames.CONFIG_ACCESSLOG + "=&" + + AttrNames.CONFIG_ERRORLOG + "="; + } + + /** + * CGI arguments used in setConfiguration() + */ + public String getCGIParamsForSetOp() { + return "op=force_set&" + toURLformat(_data); + } + + public void save() throws RemoteRequestException { + super.save(); + ResourceSet resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + String msg = resource.getString("adminop", "NeedRestart"); + ConfigInfoDialog.showDialog( + UtilConsoleGlobals.getActivatedFrame(), msg, ""); + } +} diff --git a/src/com/netscape/management/admserv/panel/CGISNMPSetup.java b/src/com/netscape/management/admserv/panel/CGISNMPSetup.java new file mode 100644 index 0000000..fda9daa --- /dev/null +++ b/src/com/netscape/management/admserv/panel/CGISNMPSetup.java @@ -0,0 +1,306 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class CGISNMPSetup extends CGIDataModel { + private static String _taskURL = "admin-serv/tasks/Configuration/SNMPSetup"; + + // String used as keys in the Hashtable for a community entry + public static final String COMMUNITY_NAME = "community"; + public static final String COMMUNITY_OPERATION = "operation"; + + // String used as keys in the Hashtable for a manager entry + public static final String MANAGER_NAME = "mananger"; + public static final String MANAGER_PORT = "port"; + public static final String MANAGER_COMMUNITY = "community"; + + public CGISNMPSetup(ConsoleInfo consoleInfo) { + super(consoleInfo, _taskURL); + } + + + public static int findEntry(Vector list, String propName, + String propValue) { + for (int i = 0; i < list.size(); i++) { + Hashtable entry = (Hashtable) list.elementAt(i); + String prop = (String) entry.get(propName); + if (prop.equals(propValue)) { + return i; + } + } + return -1; + } + + + /*************************** + * COMMUNITY Strings methods + ***************************/ + + public static Hashtable createCommunityEntry(String community, + String operation) { + Hashtable entry = new Hashtable(); + entry.put(COMMUNITY_NAME, community); + entry.put(COMMUNITY_OPERATION, operation); + return entry; + } + + /** + * Parse a comma separated list of community entries into a vector + * of hashtable entries containing parametrs (hash keys) COMMUNITY and + * OPERATION + */ + public static Vector stringToCommunityVector(String value) + throws ValidationException { + + if (value == null) { + throw new ValidationException("", "Community list is undefined"); + } + + // Dash character is used as a special value to denote an empty list + if (value.equals("-")) { + return new Vector(); + } + + Vector v = CGIDataModel.commaStringToVector(value); + for (int i = 0; i < v.size(); i++) { + String rawValue = (String) v.elementAt(i); + v.setElementAt(stringToCommunityEntry(rawValue), i); + } + return v; + } + + /** + * Parse string representation for a single community entry. The format is: + * + * where operation is ALL | SET | GET + */ + public static Hashtable stringToCommunityEntry(String value) + throws ValidationException { + String community = null, operation = null; + int idx = value.indexOf("\t"); + if (idx < 1) { + throw new ValidationException("<" + value + ">", "Field separator not found"); + } + community = value.substring(0, idx); + operation = value.substring(idx + 1); + + //Debug.println("community={" + community + "} operation={" + operation + "}"); + if (operation.equals("ALL") || operation.equals("SET") || + operation.equals("GET")) { + + return createCommunityEntry(community, operation); + } else { + throw new ValidationException("<" + operation + ">", "Bad value for operation"); + } + } + + /** + * Expand community list into String + */ + public static String communityVectorToString(Vector v) + throws ValidationException { + String value = null; + for (int i = 0; i < v.size(); i++) { + Hashtable entry = (Hashtable) v.elementAt(i); + if (value == null) { + value = communityEntryToString(entry); + } else { + value += "," + communityEntryToString(entry); + } + } + // Dash character is used as a special value to denote an empty list + return (value == null) ? "-" : value; + } + + /** + * Expand community entry into String + */ + public static String communityEntryToString(Hashtable entry) + throws ValidationException { + String value = null; + if (entry.get(COMMUNITY_NAME) == null) { + Thread.currentThread().dumpStack(); + Debug.println("Community property " + COMMUNITY_NAME + " not found"); + + } + if (entry.get(COMMUNITY_OPERATION) == null) { + Thread.currentThread().dumpStack(); + Debug.println("Community property " + COMMUNITY_OPERATION + + " not found"); + + } + value = (String) entry.get(COMMUNITY_NAME) + "\t" + + (String) entry.get(COMMUNITY_OPERATION); + return value; + } + + + /*************************** + * SNMP MANAGER methods + ***************************/ + + public static Hashtable createManagerEntry(String manager, + String port, String community) { + Hashtable entry = new Hashtable(); + entry.put(MANAGER_NAME, manager); + entry.put(MANAGER_PORT, port); + entry.put(MANAGER_COMMUNITY, community); + return entry; + } + + /** + * Parse a comma separated list of manager entries into a vector + * of hashtable entries containing parametrs (hash keys) MANAGER and + * PORT + */ + public static Vector stringToManagerVector(String value) + throws ValidationException { + + if (value == null) { + throw new ValidationException("", "Manager list is undefined"); + } + + // Dash character is used as a special value to denote an empty list + if (value.equals("-")) { + return new Vector(); + } + + Vector v = CGIDataModel.commaStringToVector(value); + for (int i = 0; i < v.size(); i++) { + String rawValue = (String) v.elementAt(i); + v.setElementAt(stringToManagerEntry(rawValue), i); + } + return v; + } + + /** + * Parse string representation for a single manager entry. The format is: + * + */ + public static Hashtable stringToManagerEntry(String value) + throws ValidationException { + String manager = null, port = null, community = null; + int tab1 = value.indexOf("\t"); + if (tab1 < 1) { + throw new ValidationException("<" + value + ">", "Field separator not found"); + } + int tab2 = value.indexOf("\t", tab1 + 1); + if (tab2 < 1) { + throw new ValidationException("<" + value + ">", "Second field separator not found"); + } + + manager = value.substring(0, tab1); + port = value.substring(tab1 + 1, tab2); + community = value.substring(tab2 + 1); + + Debug.println("manager={" + manager + "} port={" + port + + "} community={" + community + "}"); + try { + int portValue = Integer.parseInt(port); + if (portValue < 1 || portValue > 65535) { + ResourceSet rs = new ResourceSet("com.netscape.management.admserv.panel.panel"); + String msg = rs.getString("common","PortRange"); + throw new ValidationException("", msg); + } + } catch (Exception ex) { + ResourceSet rs = new ResourceSet("com.netscape.management.admserv.panel.panel"); + String msg = rs.getString("common","PortRange"); + throw new ValidationException("", msg); + } + + + return createManagerEntry(manager, port, community); + } + + /** + * Expand manager list into String + */ + public static String managerVectorToString(Vector v) + throws ValidationException { + String value = null; + for (int i = 0; i < v.size(); i++) { + Hashtable entry = (Hashtable) v.elementAt(i); + if (value == null) { + value = managerEntryToString(entry); + } else { + value += "," + managerEntryToString(entry); + } + } + // Dash character is used as a special value to denote an empty list + return (value == null) ? "-" : value; + } + + /** + * Expand manager entry into String + */ + public static String managerEntryToString(Hashtable entry) + throws ValidationException { + String value = null; + if (entry.get(MANAGER_NAME) == null) { + Thread.currentThread().dumpStack(); + Debug.println("Manager property " + MANAGER_NAME + " not found"); + + } + if (entry.get(MANAGER_PORT) == null) { + Thread.currentThread().dumpStack(); + Debug.println("Manager property " + MANAGER_PORT + " not found"); + + } + if (entry.get(MANAGER_COMMUNITY) == null) { + Thread.currentThread().dumpStack(); + Debug.println("Manager community " + MANAGER_COMMUNITY + " not found"); + + } + + value = (String) entry.get(MANAGER_NAME) + "\t" + + (String) entry.get(MANAGER_PORT) + "\t" + + (String) entry.get(MANAGER_COMMUNITY); + return value; + } + + /** + * CGI arguments used in getConfiguration() + */ + public String getCGIParamsForGetOp() { + return "op=getconfig"; + } + + /** + * CGI arguments used in setConfiguration() + */ + public String getCGIParamsForSetOp() { + String result = "op=setconfig&" + toURLformat(_data); + Debug.println("SNMPConfigData.getCGIParamsForSetOp=<" + + result + ">"); + return result; + } +} diff --git a/src/com/netscape/management/admserv/panel/CGIServerSetup.java b/src/com/netscape/management/admserv/panel/CGIServerSetup.java new file mode 100644 index 0000000..1bdf826 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/CGIServerSetup.java @@ -0,0 +1,210 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class CGIServerSetup extends CGIDataModel { + private static String _taskURL = "admin-serv/tasks/Configuration/ServerSetup"; + + private String _portValue = null; + private String _addrValue = null; + + public CGIServerSetup(ConsoleInfo consoleInfo) { + super(consoleInfo, _taskURL); + } + + public void setAttribute(String attr, + String val) throws ValidationException { + super.setAttribute(attr, val); + } + + + /** + * Encode a list of IP addr or host names to allow in the form of regular expression + */ + public static String encodeFilterList(Vector members) { + String regex; + int size = members.size(); + if (size == 0) { + regex = ""; + } else if (size == 1) { + regex = (String) members.elementAt(0); + } else { + regex = "("; + for (int i = 0; i < size; i++) { + if (i == 0) { + regex += (String) members.elementAt(i); + } else { + regex += "|" + (String) members.elementAt(i); + } + } + regex += ")"; + } + Debug.println("encodeFilterList=" + regex); + return regex; + } + + /** + * Decode a regular expression into the list; Expected format is "(exter1|entry2|entry3)" or + * just "entry" + * + */ + public static Vector parseFilterList(String regex) { + Vector list = new Vector(); + if (regex == null || regex.length() == 0) { + ; // nothing to do + } else if (regex.startsWith("(") && regex.endsWith(")")) { + String members = regex.substring(1, regex.length() - 1); + Debug.println("members=" + members); + StringTokenizer strtok = new StringTokenizer(members, "|"); + while (strtok.hasMoreTokens()) { + list.addElement(strtok.nextToken()); + } + } else { + list.addElement(regex); + } + return list; + } + + /** + * CGI arguments used in getConfiguration() + */ + public String getCGIParamsForGetOp() { + //return "op=get&configuration="; + return "op=get&" + AttrNames.CONFIG_SERVERPORT + "=&" + + AttrNames.CONFIG_SERVERADDRESS + "=&" + + AttrNames.CONFIG_HOSTS + "=&" + + AttrNames.CONFIG_ADDRESSES + "=&" + + AttrNames.CONFIG_DSGW + "=&" + + AttrNames.CONFIG_USER + "="; + + } + + /** + * CGI arguments used in setConfiguration() + */ + public String getCGIParamsForSetOp() { + String op = "op=force_set&"; + Enumeration e = _data.keys(); + while (e.hasMoreElements()) { + String name = (String) e.nextElement(); + String value = (String)_data.get(name); + + if (name.equals(AttrNames.CONFIG_SERVERPORT) && + value.equals(_portValue)) { + continue; + } + + if (name.equals(AttrNames.CONFIG_SERVERADDRESS) && + (_addrValue==null) && (value.length()==0)) { + continue; + } + + op += name + "=" + URLByteEncoder.encodeUTF8(value) + + (e.hasMoreElements() ? "&":""); + } + + return op; + } + + public void load() throws RemoteRequestException { + super.load(); + if (getAttribute(AttrNames.CONFIG_DSGW) == null) { + _data.put(AttrNames.CONFIG_DSGW, "on"); + _origData.put(AttrNames.CONFIG_DSGW, "on"); + } + + _portValue = getAttribute(AttrNames.CONFIG_SERVERPORT); + _addrValue = getAttribute(AttrNames.CONFIG_SERVERADDRESS); + + } + + public void save() throws RemoteRequestException { + super.save(); + + String newPort = getAttribute(AttrNames.CONFIG_SERVERPORT); + String newAddr = getAttribute(AttrNames.CONFIG_SERVERADDRESS); + boolean portChanged = false, addrChanged=false; + Debug.println("newAddr=<"+newAddr + "> prevAddr=<"+_addrValue + ">"); + + if (_portValue != null && !_portValue.equals(newPort)) { + portChanged = true; + _portValue = newPort; + } + + if ((_addrValue == null || _addrValue.length() == 0)) { + // no listen address was previously configured + addrChanged = (newAddr.length() != 0); + _addrValue = newAddr; + } + else { + // listen address was previously configured + addrChanged = !_addrValue.equals(newAddr); + _addrValue = newAddr; + } + + if (portChanged || addrChanged) { + ResourceSet resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + String msg = resource.getString("adminop", "NeedRestartReconnect"); + ConfigInfoDialog.showDialog(getDialogParent(), msg, ""); + + //Create post restart adminURL which is needed for RestartOperation. + try { + URL url = new URL(_consoleInfo.getAdminURL()); + String host = (addrChanged && newAddr.length() != 0) ? + newAddr : url.getHost(); + String port = portChanged ? + newPort : String.valueOf(url.getPort()); + String postRestartURL = + url.getProtocol() + "://" + host + ":" + port + "/"; + + Debug.println("oldURL = " + + _consoleInfo.getAdminURL() + " postRestartURL = " + + postRestartURL); + + IRestartControl restartControl = + (IRestartControl)_consoleInfo.get( + IRestartControl.ID); + if (restartControl != null) { + restartControl.setPostRestartURL(postRestartURL); + } + } catch (Exception e) { + Debug.println("postRestartURL " + e); + } + } + else { + ResourceSet resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + String msg = resource.getString("adminop", "NeedRestart"); + ConfigInfoDialog.showDialog(getDialogParent(), msg, ""); + } + + } +} diff --git a/src/com/netscape/management/admserv/panel/CGIUGDirectorySetup.java b/src/com/netscape/management/admserv/panel/CGIUGDirectorySetup.java new file mode 100644 index 0000000..8b80072 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/CGIUGDirectorySetup.java @@ -0,0 +1,96 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class CGIUGDirectorySetup extends CGIDataModel { + private static String _taskURL = "admin-serv/tasks/Configuration/UGDirectorySetup"; + + public CGIUGDirectorySetup(ConsoleInfo consoleInfo) { + super(consoleInfo, _taskURL); + } + + /** + * CGI arguments used in getConfiguration() + */ + public String getCGIParamsForGetOp() { + return "op=getconfig"; + } + + /** + * CGI arguments used in setConfiguration() + */ + + public String getCGIParamsForSetOp() { + String param = "op=setconfig&"; + String inforef = getAttribute(AttrNames.UGDSCONFIG_INFOREF); + Debug.println("save info ref=" + inforef); + if (inforef != null && inforef.length() > 0) { + param += AttrNames.UGDSCONFIG_INFOREF + "=" + inforef; + } else { + String name = AttrNames.UGDSCONFIG_DIRURL; + String value = getAttribute(name); + param += name + "=" + value + "&"; + name = AttrNames.UGDSCONFIG_BINDDN; + value = getAttribute(name); + param += name + "=" + value + "&"; + name = AttrNames.UGDSCONFIG_BINDPW; + value = getAttribute(name); + param += name + "=" + value; + } + return param; + } + + public void load() throws RemoteRequestException { + super.load(); + String inforef = (String)_data.get(AttrNames.UGDSCONFIG_INFOREF); + // Replace the actual ref dn with the keyword "default" which is used by + // the UGDirectory panel and recognized by the backend CGI + if (inforef != null && inforef.length() > 0) { + _data.put(AttrNames.UGDSCONFIG_INFOREF, "default"); + _origData.put(AttrNames.UGDSCONFIG_INFOREF, "default"); + } + } + + public void save() throws RemoteRequestException { + + super.save(); + + ResourceSet resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + String msg1 = resource.getString("adminop", "ldapds-Changed"); + String msg2 = resource.getString("adminop", "ldapds-ChangedInfo"); + String title = resource.getString("adminop", "ldapds-UGGroupbox"); + ConfigInfoDialog.showDialog(getDialogParent(), + msg1 + "\n\n" + msg2, title); + + } + +} diff --git a/src/com/netscape/management/admserv/panel/DialogFrame.java b/src/com/netscape/management/admserv/panel/DialogFrame.java new file mode 100644 index 0000000..8cc7996 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/DialogFrame.java @@ -0,0 +1,82 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.awt.*; +import java.util.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.client.util.*; +import com.netscape.management.admserv.config.*; + +/** + * @version 0.1 12/15/97 + * @author miodrag@netscape.com + */ +public class DialogFrame extends AbstractDialog { + + private Component _parent; + public DialogFrame(Component parent, String title, Component comp) { + super(ConfigErrorDialog.getParentFrame(parent), title, + /*modal=*/true); + _parent = parent; + setPanel((JPanel) comp); + pack(); + setMinimumSize(getSize()); + addWindowListener(_winListener); + } + + /*public void setVisible(boolean show) { + if (show) { + ConfigErrorDialog.setDialogLocation(this, _parent); + } + super.setVisible(show); + }*/ + + private WindowListener _winListener = new WindowAdapter() { + public void windowClosing(WindowEvent e) { + DialogFrame.this.setVisible(false); + } + }; + + private boolean _busyCursorOn; + + /** + * Override setCursor to show busy cursor correctly + */ + public void setCursor(Cursor cursor) { + if (_busyCursorOn && cursor.getType() != Cursor.WAIT_CURSOR) { + Debug.println(9, "DialogFrame.setCursor(): Discarding change of cursor"); + return; + } + super.setCursor(cursor); + } + + /** + * Force the cursor for the whole frame to be busy. + * See how _busyCursorOn flag is used inside setCursor + */ + public void setBusyCursor(boolean isBusy) { + _busyCursorOn = isBusy; + super.setCursor( Cursor.getPredefinedCursor(isBusy ? + Cursor.WAIT_CURSOR : Cursor.DEFAULT_CURSOR)); + } +} diff --git a/src/com/netscape/management/admserv/panel/DirectoryConfigPanel.java b/src/com/netscape/management/admserv/panel/DirectoryConfigPanel.java new file mode 100644 index 0000000..cfd6e23 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/DirectoryConfigPanel.java @@ -0,0 +1,316 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.nmclf.SuiConstants; + +/** + * + * @version 0.1 11/23/97 + * @author miodrag@netscape.com + */ +public class DirectoryConfigPanel extends PluginConfigPanel implements SuiConstants { + + IConfigDataModel _configData; + String _defaultPort = "389"; + String _defaultSSLPort = "636"; + + static ResourceSet _resource; + static String _i18nHost, _i18nPort, _i18nDSGroupbox, _i18nUseSSL; + static String _i18nEnterLdapHost, _i18nEnterLdapPort, _i18nPortRange; + static String _i18nWarnMigrate, _i18nWarnCert; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nDSGroupbox = _resource.getString("ldapds","DSGroupbox"); + _i18nHost = _resource.getString("ldapds","DSHost"); + _i18nPort = _resource.getString("ldapds","Port"); + _i18nUseSSL = _resource.getString("ldapds","UseSSL"); + _i18nEnterLdapHost = _resource.getString("ldapds","EnterLdapHost"); + _i18nEnterLdapPort = _resource.getString("ldapds","EnterLdapPort"); + _i18nPortRange = _resource.getString("common","PortRange"); + _i18nWarnMigrate = _resource.getString("ldapds","WarnMigrate"); + ; + _i18nWarnCert = _resource.getString("ldapds","WarnCert"); + ; + } + + Help _help; + + public static final int topInset = COMPONENT_SPACE, + rghtColInset = DIFFERENT_COMPONENT_SPACE; + + JLabel _lblHost, _lblPort; + JCheckBox _cbSSL; + JTextField _txtPort; + SingleByteTextField _txtHost; + + public DirectoryConfigPanel(String title, IConfigDataModel data) { + super(title); + _configData = (IConfigDataModel) data; + + setLayout(new BorderLayout()); + add(makeConfigPanel(), BorderLayout.NORTH); + _help = new Help(_resource); + } + + public void showHelp() { + _help.contextHelp("ldapHelp"); + } + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) { + _configData = (IConfigDataModel) data; + if (_configData.isLoaded()) { + setPanelContent(_configData); + } + } + + public void initialize() throws RemoteRequestException { + if (!_configData.isLoaded()) + _configData.load(); + setPanelContent(_configData); + _cbSSL.addActionListener(_cbSSLListener); + } + + public void resetContent() { + setPanelContent(_configData); + } + + public void applyChanges() throws ConfigPanelException { + getPanelContent(_configData); + } + + public void registerEditComponents(EditMonitor editMonitor) { + editMonitor.monitor(_txtPort); + editMonitor.monitor(_txtHost); + editMonitor.monitor(_cbSSL); + } + + public void setPanelContent(IConfigDataModel data) { + setLDAPHost(data.getAttribute(AttrNames.DSCONFIG_HOST)); + setLDAPPort(data.getAttribute(AttrNames.DSCONFIG_PORT)); + setSSL(data.getAttribute(AttrNames.DSCONFIG_SSL)); + } + + ActionListener _cbSSLListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (_cbSSL.isSelected() && + _txtPort.getText().equals(_defaultPort)) { + _txtPort.setText(_defaultSSLPort); + } else if (!_cbSSL.isSelected() && + _txtPort.getText().equals(_defaultSSLPort)) { + _txtPort.setText(_defaultPort); + } + } + }; + + + String getSSL() { + return _cbSSL.isSelected() ? "true" : "false"; + } + + void setSSL(String booleanFlag) { + _cbSSL.setSelected(booleanFlag != null && booleanFlag.equals("true")); + } + + void setLDAPHost(String host) { + _txtHost.setText(host == null ? "" : host); + } + + void setLDAPPort(String port) { + _txtPort.setText(port == null ? "" : port); + } + + public void getPanelContent(IConfigDataModel data) + throws ConfigPanelException { + String host = _txtHost.getText().trim(); + String port = _txtPort.getText().trim(); + + if (host.length() == 0) { + throw new ValidationException("", _i18nEnterLdapHost); + } else if (port.length() == 0) { + throw new ValidationException("", _i18nEnterLdapPort); + } + + int portNum = -1; + + try { + portNum = Integer.parseInt(port); + if (portNum < 1 || portNum > 65535) { + throw new ValidationException("",_i18nPortRange); + } + } catch (Exception e) { + throw new ValidationException("",_i18nPortRange); + } + + // Try to connect to the DS to see if it is a valid one + try { + LDAPUtil.validateLDAPParams(host, portNum, + _cbSSL.isSelected(), null, null, null); + } catch (IllegalArgumentException e) { + throw new ValidationException("", e.getMessage()); + } + + data.setAttribute(AttrNames.DSCONFIG_HOST, host); + data.setAttribute(AttrNames.DSCONFIG_PORT, port); + data.setAttribute(AttrNames.DSCONFIG_SSL, getSSL()); + + if (data instanceof AdminConfigData) { + ((AdminConfigData) data).setDialogParent(this); // For ack dialog + } + } + + /** + * Override BaseEditPanel.makeConfigPanel() to provide a custom panel, + * called by baseEditPanel constructor + */ + protected JComponent makeConfigPanel() { + JPanel p = new JPanel(); + GBC gbc = new GBC(); + GridBagLayout gbl; + JPanel ctrlGroup; + + p.setLayout(gbl = new GridBagLayout()); + + //gbc.setInsets(topInset,leftColInset,0,0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GridBagConstraints.WEST, //anchor + GridBagConstraints.HORIZONTAL); //fill + p.add(createServerGroup(), gbc); + + return p; + } + + private JPanel createServerGroup() { + GridBagLayout gbl; + GBC gbc = new GBC(); + JPanel group = new JPanel(gbl = new GridBagLayout()); + group.setBorder( + BaseConfigPanel.createGroupBorder(_i18nDSGroupbox)); + int row = 0; + + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, row, 3, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(createInfoMessage(), gbc); + row++; + + _lblHost = new JLabel(_i18nHost); + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + group.add(_lblHost, gbc); + + _txtHost = new SingleByteTextField(16); + gbc.setInsets(0, rghtColInset, 0, 0); + gbc.setGrid(1, row, 2, 1); + gbc.setSpace(0.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(_txtHost, gbc); + _lblHost.setLabelFor(_txtHost); + row++; + + _lblPort = new JLabel(_i18nPort); + gbc.setInsets(topInset, 0, 0, 0); + gbc.setGrid(0, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, //anchor + GBC.NONE); //fill + group.add(_lblPort, gbc); + + _txtPort = new JTextField("389",6); + _txtPort.setDocument(FilteredInputDocument.allowDigitsOnly()); + gbc.setInsets(topInset, rghtColInset, 0, 0); + gbc.setGrid(1, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(_txtPort, gbc); + _lblPort.setLabelFor(_txtPort); + + _cbSSL = new JCheckBox(_i18nUseSSL, false); + gbc.setInsets(topInset, rghtColInset * 2, 0, 0); + gbc.setGrid(2, row, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.NONE); //fill + group.add(_cbSSL, gbc); + + return group; + } + + private JPanel createInfoMessage() { + GridBagLayout gbl; + GBC gbc = new GBC(); + JPanel group = new JPanel(gbl = new GridBagLayout()); + int row = 0; + MultilineLabel mll; + JLabel refLabel = new JLabel(); // unsed only for font + + gbc.setInsets(0, COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, row, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + group.add(mll = new MultilineLabel(_i18nWarnMigrate, 1, 36), gbc); + mll.setFont(refLabel.getFont()); + row++; + + gbc.setInsets(COMPONENT_SPACE, COMPONENT_SPACE, + DIFFERENT_COMPONENT_SPACE, 0); + gbc.setGrid(1, row, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + group.add(mll = new MultilineLabel(_i18nWarnCert, 1, 36), gbc); + mll.setFont(refLabel.getFont()); + row++; + + return group; + } + + + public void setPort(String port) { + _txtPort.setText((port != null) ? port : ""); + } + + public String getPort() { + String port = _txtPort.getText(); + return port; + } + + public void setHost(String host) { + _txtHost.setText((host != null) ? host : ""); + } + + public String getHost() { + String host = _txtHost.getText(); + return host; + } +} + diff --git a/src/com/netscape/management/admserv/panel/EditableList.java b/src/com/netscape/management/admserv/panel/EditableList.java new file mode 100644 index 0000000..9f90842 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/EditableList.java @@ -0,0 +1,579 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.border.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.*; +import com.netscape.management.nmclf.*; + +/** + * A generic class that implements an editable list with buttons add, edit + * and remove. A list entry is edited in a custom popup dialog. The list + * entry details can be shown in a custom group box panel which is placed + * below (south) of the list and command buttons. +*/ + +/** + * + * @version 0.1 11/23/97 + * @author miodrag@netscape.com + */ +public abstract class EditableList extends JPanel implements SuiConstants { + + static ResourceSet _resource; + static String _i18nAddButton, _i18nEditButton, _i18nRemoveButton; + static String _i18nOKButton, _i18nCancelButton; + static String _i18nAddDefaultToolTip, _i18nEditDefaultToolTip, _i18nRemoveDefaultToolTip; + static String _i18nOKDefaultToolTip, _i18nCancelDefaultToolTip, _i18nHelpDefaultToolTip; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nAddButton = _resource.getString("editlist","AddButton"); + _i18nEditButton = _resource.getString("editlist","EditButton"); + _i18nRemoveButton = _resource.getString("editlist","RemoveButton"); + _i18nOKButton = _resource.getString("editlist","OKButton"); + _i18nCancelButton = _resource.getString("editlist","CancelButton"); + _i18nAddDefaultToolTip = _resource.getString("editlist","AddDefaultToolTip"); + _i18nEditDefaultToolTip = _resource.getString("editlist","EditDefaultToolTip"); + _i18nRemoveDefaultToolTip = _resource.getString("editlist","RemoveDefaultToolTip"); + _i18nOKDefaultToolTip = _resource.getString("editlist","OKDefaultToolTip"); + _i18nCancelDefaultToolTip = _resource.getString("editlist","CancelDefaultToolTip"); + _i18nHelpDefaultToolTip = _resource.getString("editlist","HelpDefaultToolTip"); + } + + protected JList _list; + protected DefaultListModel _listModel; + protected JScrollPane _listScroller; + protected ButtonBar _buttons; + protected ItemEditDialog _editDialog; + protected JPanel _detailsPanel, _editPanel; + static protected String _cmdAdd = "add", _cmdEdit = "edit", + _cmdRemove = "remove"; + protected JPanel _north, _south; + + + /** + * A compoent to request focus when the dialog is shown + */ + public JComponent _initialFocusComponent; + + /** + * List of text fields where key press should be treated as dialog edit commit, + * i.e. equivalent as if the user has pressed OK button + */ + public JTextField[]_commitOnEnterComponents; + + + public EditableList() { + //setLayout(new BorderLayout(0, 10)); + setLayout( new BorderLayout(0, + /*vgap=*/SuiLookAndFeel.SEPARATED_COMPONENT_SPACE)); + createLayout(); + } + + protected void finalize() { + if (_editDialog != null) { + _editDialog.dispose(); + ModalDialogUtil.sleep(); + } + } + + public void addListDataListener(ListDataListener listener) { + _listModel.addListDataListener(listener); + } + + public void removeListDataListener(ListDataListener listener) { + _listModel.removeListDataListener(listener); + } + + + private void createLayout() { + + setBorder( BorderFactory.createEmptyBorder( + DIFFERENT_COMPONENT_SPACE, 0, 0, 0)); + + //_north = new JPanel(new BorderLayout(0, 10)); + _north = new JPanel(new BorderLayout(DIFFERENT_COMPONENT_SPACE, 0)); + + // list + _list = new JList(); + _list.setModel(_listModel = new DefaultListModel()); + _list.addListSelectionListener(_selectListener); + _list.addMouseListener(_dblclkListener); + _list.setVisibleRowCount(5); + _list.setBackground(Color.white); + _listScroller = new JScrollPane(); + _listScroller.getViewport().setView(_list); + _listScroller.setBorder(BorderFactory.createLoweredBevelBorder()); + + // buttons + _buttons = new ButtonBar(new String[]{_cmdAdd, _cmdEdit, _cmdRemove}, + new String[]{_i18nAddButton, _i18nEditButton, _i18nRemoveButton}, + new String[]{getAddToolTip(), getEditToolTip(), getRemoveToolTip()}, + false); + _buttons.addActionListener(_btnListener); + _buttons.getButton(_cmdEdit).setEnabled(false); + _buttons.getButton(_cmdRemove).setEnabled(false); + + _north.add(_listScroller, BorderLayout.CENTER); + _north.add(_buttons, BorderLayout.EAST); + + //detals + _detailsPanel = getDetailsPanel(); + + add(_north, BorderLayout.CENTER); + if (_detailsPanel != null) { + _south = new JPanel(new BorderLayout()); + _south.setBorder( + BaseConfigPanel.createGroupBorder(getDetailsTitle())); + _south.add(_detailsPanel); + add(_south, BorderLayout.SOUTH); + } + + _editPanel = getEditPanel(); + } + + int findItemIndex(String item) { + for (int i = 0; i < _listModel.getSize(); i++) { + String curItem = (String)_listModel.getElementAt(i); + if (curItem.equals(item)) { + return i; + } + } + return -1; + } + + void addItem(String item) { + if (item.length() == 0) + return; + if (findItemIndex(item) == -1) { + createItem(item); + _listModel.addElement(item); + } else { + updateItem(item, false); + } + selectItem(item); + _list.setSelectedIndex(findItemIndex(item)); + } + + void processEditOperation(String item) { + int idx = _list.getSelectedIndex(); + if (idx < 0) { + return; + } else if (item.length() == 0) { + _listModel.removeElementAt(idx); + removeItem(item); + } else { + String itemOldName = (String)_listModel.getElementAt(idx); + boolean isRenamed = !itemOldName.equals(item); + _listModel.setElementAt(item, idx); + updateItem(itemOldName, isRenamed); + _list.setSelectedIndex(findItemIndex(item)); + if (isRenamed) + _list.repaint(); + } + } + + // A check for a JFC 0.5.1 bug; If the last element in the list is deleted, + // no element is selected, but the call getSelectedIndex() returns the + // index of the non-existing element that was just deleted + int getSelectedIndex() { + int idx = _list.getSelectedIndex(); + return (idx < _listModel.size()) ? idx : -1; + } + + void adjustSelection() { + int idx = getSelectedIndex(); + _buttons.getButton(_cmdEdit).setEnabled(idx >= 0); + _buttons.getButton(_cmdRemove).setEnabled(idx >= 0); + selectItem((idx >= 0) ? (String)_listModel.getElementAt(idx) : + null); + } + + ListSelectionListener _selectListener = new ListSelectionListener() { + public void valueChanged(ListSelectionEvent e) { + if (!e.getValueIsAdjusting()) { + EditableList.this.adjustSelection(); + } + } + }; + + + protected void createEditDialog(boolean setAddTitle) { + if (setAddTitle) { + _editDialog = new ItemEditDialog(_north, getAddTitle(), + _editPanel, this); + } else { + _editDialog = new ItemEditDialog(_north, getEditTitle(), + _editPanel, this); + } + _editDialog.setHelpResourceSet(getHelpResourceSet()); + _editDialog.setHelpToken(getHelpToken()); + } + + + /** + * Edit a list member when double-clicked + */ + MouseListener _dblclkListener = new MouseAdapter () { + public void mousePressed(MouseEvent e) { + if (e.getClickCount() == 2) { + JList list = (JList) e.getSource(); + int idx = list.locationToIndex(e.getPoint()); + + if (idx >= 0) { + createEditDialog(false); + String item = + (String)_listModel.getElementAt(idx); + setEditPanelParameters(item); + while (true) { + _editDialog.setVisible(true); + if (_editDialog.getCommand().equals( + ButtonBar.cmdOK)) { + try { + validateEdit(); + String newName = + getEditPanelItem().trim(); + processEditOperation(newName); + break; + } catch (ValidationException ex) { + ConfigErrorDialog.showDialog( + _north, ex); + } + } else { + break; + } + } + } + } + } + }; + + + ActionListener _btnListener = new ActionListener() { + + public void actionPerformed(ActionEvent e) { + + int idx = getSelectedIndex(); + String cmd = e.getActionCommand(); + + if (cmd.equals(_cmdAdd)) { + createEditDialog(true); + setEditPanelParameters(null); + while (true) { + _editDialog.setVisible(true); + if (_editDialog.getCommand().equals( + ButtonBar.cmdOK)) { + try { + validateEdit(); + String item = getEditPanelItem().trim(); + addItem(item); + break; + } catch (ValidationException ex) { + ConfigErrorDialog.showDialog( + _north, ex); + } + } else { + break; } + } + } + else if (cmd.equals(_cmdEdit)) { + createEditDialog(false); + if (idx >= 0) { + String item = + (String)_listModel.getElementAt(idx); + setEditPanelParameters(item); + while (true) { + _editDialog.setVisible(true); + if (_editDialog.getCommand().equals( + ButtonBar.cmdOK)) { + try { + validateEdit(); + String newName = + getEditPanelItem().trim(); + processEditOperation(newName); + break; + } catch (ValidationException ex) { + ConfigErrorDialog.showDialog( + _north, ex); + } + } else { + break; + } + } + } + } + else if (cmd.equals(_cmdRemove)) { + if (idx >= 0) { + removeItem( + (String)_listModel.getElementAt(idx)); + _listModel.removeElementAt(idx); + } + } + + EditableList.this.adjustSelection(); + + } + }; + + public void setList(Vector v) { + _listModel.removeAllElements(); + for (int i = 0; i < v.size(); i++) { + _listModel.addElement(v.elementAt(i)); + } + _buttons.getButton(_cmdEdit).setEnabled(false); + _buttons.getButton(_cmdRemove).setEnabled(false); + if (v.size() > 0) { + _list.setSelectedIndex(0); + _buttons.getButton(_cmdEdit).setEnabled(true); + _buttons.getButton(_cmdRemove).setEnabled(true); + } + } + + public Vector getList() { + Vector v = new Vector(); + for (int i = 0; i < _listModel.getSize(); i++) { + v.addElement(_listModel.getElementAt(i)); + } + return v; + } + + /** + * A panel that shows details for the selected entry in the list + */ + abstract public JPanel getDetailsPanel(); + abstract public String getDetailsTitle(); + + /** + * A custom panel to be shown in the edit dialog + */ + abstract public JPanel getEditPanel(); + abstract public String getEditTitle(); + abstract public String getAddTitle(); + abstract public ResourceSet getHelpResourceSet(); + abstract public String getHelpToken(); + abstract public void validateEdit() throws ValidationException; + + /** + * Custom Tool Tips to Display + */ + protected String getEditToolTip() { + return _i18nEditDefaultToolTip; + } + + protected String getAddToolTip() { + return _i18nAddDefaultToolTip; + } + + protected String getRemoveToolTip() { + return _i18nRemoveDefaultToolTip; + } + + /** + * A method called to populate the contents of edit panel. + * Paremeter item is null for ADD operation. A + * non-null string is passed for EDIT operation + */ + abstract public void setEditPanelParameters(String item); + + /** + * A method called to craete a new item. The item parameters should + * be read from the custom edit panel + */ + abstract public void createItem(String name); + + /** + * A method called to update an item. The item parameters should + * be read from the custom edit panel + */ + abstract public void updateItem(String name, boolean isRenamed); + + /** + * A method called to remove an item. + */ + abstract public void removeItem(String name); + + /** + * A method called when an item is selected + */ + abstract public void selectItem(String item); + + + /** + * A method called to read the item from the edit panel + */ + abstract public String getEditPanelItem(); + + /** + * A method to set initial focus + */ + public void setEditPanelInitalFocusComponent(JComponent c) { + _initialFocusComponent = c; + } + + public void setEditPanelCommitOnEnterComponents( + JTextField[] components) { + _commitOnEnterComponents = components; + } + + + +} + +/** + * Item Edit Dialog + */ +class ItemEditDialog extends AbstractDialog { + String _cmd = ""; + ButtonBar _buttons; + final Component _parent; + final JPanel _editPanel; + final EditableList _editList; + ResourceSet _helpResourceSet; + String _helpToken; + + public ItemEditDialog(Component parent, String title, + JPanel editPanel, EditableList editList) { + super(SuiOptionPane.getFrameForComponent(parent), title, + /*modal=*/true); + _parent = parent; + getContentPane().add(createLayout(_editPanel = editPanel)); + _editList = editList; + pack(); + Dimension size = getSize(); + setMinimumSize(size); + + // This size make the dialog look better then when it is packed + if (size.width < 320) { + size.width = 320; + setSize(size); + } + + addWindowListener(_winListener); + _buttons.addActionListener(_actionListener); + } + + public void setHelpResourceSet(ResourceSet rs) { + _helpResourceSet = rs; + } + + public void setHelpToken(String token) { + _helpToken = token; + } + + private boolean _firstCall = true; + + public void setVisible(boolean show) { + if (show && _firstCall) { + if (_editList._initialFocusComponent != null) { + _editList._initialFocusComponent.requestFocus(); + } + if (_editList._commitOnEnterComponents != null) { + for (int i = 0; + i < _editList._commitOnEnterComponents.length; + i++) { + _editList._commitOnEnterComponents[i] + .addKeyListener(_keyListener); + } + } + _firstCall = false; + } + super.setVisible(show); + } + + private KeyListener _keyListener = new KeyAdapter() { + public void keyPressed (KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { + _cmd = ButtonBar.cmdCancel; + ItemEditDialog.this.setVisible(false); + } else if (e.getKeyCode() == KeyEvent.VK_ENTER) { + _cmd = ButtonBar.cmdOK; + ItemEditDialog.this.setVisible(false); + } + } + }; + + + private WindowListener _winListener = new WindowAdapter() { + public void windowClosing(WindowEvent e) { + _cmd = ButtonBar.cmdCancel; + ItemEditDialog.this.setVisible(false); + } + }; + + + protected void showHelp() { + if (_helpResourceSet != null && _helpToken != null) { + (new Help(_helpResourceSet)).contextHelp(_helpToken); + } + } + + private ActionListener _actionListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + _cmd = e.getActionCommand(); + if (_cmd.equals(ButtonBar.cmdHelp)) { + showHelp(); + } else { + ItemEditDialog.this.setVisible(false); + } + } + }; + + private JPanel createLayout(JPanel editPanel) { + JPanel p = new JPanel(new BorderLayout()); + + GBC gbc = new GBC(); + JPanel north = new JPanel(new GridBagLayout()); + + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(1.0, 1.0, GBC.WEST, //anchor + GBC.BOTH); //fill + north.add(editPanel, gbc); + + p.add(north, BorderLayout.NORTH); + _buttons = + new ButtonBar(new String[]{ButtonBar.cmdOK, ButtonBar.cmdCancel, null, ButtonBar.cmdHelp}, + new String[]{ EditableList._i18nOKButton, EditableList._i18nCancelButton, null, + ButtonBar._i18nHelpButton}, + new String[]{EditableList._i18nOKDefaultToolTip, EditableList._i18nCancelDefaultToolTip, + null, EditableList._i18nHelpDefaultToolTip}, + true); + + _buttons.setBorder( new EmptyBorder( + SuiLookAndFeel.SEPARATED_COMPONENT_SPACE, 0, 0, 0)); + p.add(_buttons, BorderLayout.SOUTH); + + return p; + } + + public String getCommand() { + return _cmd; + } +} diff --git a/src/com/netscape/management/admserv/panel/IAdminOperationListener.java b/src/com/netscape/management/admserv/panel/IAdminOperationListener.java new file mode 100644 index 0000000..17f418d --- /dev/null +++ b/src/com/netscape/management/admserv/panel/IAdminOperationListener.java @@ -0,0 +1,29 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import com.netscape.management.client.console.ConsoleInfo; +/** + * + */ +public interface IAdminOperationListener { + public void cgiRequestCompleted(ConsoleInfo ci); +} diff --git a/src/com/netscape/management/admserv/panel/IRestartControl.java b/src/com/netscape/management/admserv/panel/IRestartControl.java new file mode 100644 index 0000000..520dd8c --- /dev/null +++ b/src/com/netscape/management/admserv/panel/IRestartControl.java @@ -0,0 +1,107 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +/** + * Interface used to control restart parameters for the Admin Server. + * + */ + +public interface IRestartControl { + + /** + * Restart activator ID. To be used as a key when a restart activator is stored in ConsoleInfo + * IRestartControl acivator = (IRestartControl) _consoleInfo.get(IRestartControl.ID); + */ + public static final String ID = "RESTART_CONTROL"; + + /** + * Set the state of the "needsAutoRestart" flag + * The Flag is used to indicate that the server must be restarted because of + * configuration changes. The activator is supposed to restart the server when + * it is clear that the user did not explicitly reqest a restart: this would usually + * be the case when the server configurataion window is closed. + * + * @param flag true=needs restart, false=does not need restart + */ + public void setNeedsAutoRestart(boolean flag); + + /** + * Return the state of the "needsAutoRestart" flag + * + * @returns "needsAutoRestart" flag for the server + */ + public boolean needsAutoRestart(); + + /** + * Set the state of the "CanRestartFromConsole" flag + * The Flag is used to indicate if the server can be restarted remotly from the console. + * If false, the server can be restarted only locally from the command line + * + * @param flag true=can restart, false=can not need restart + */ + public void setCanRestartFromConsole(boolean flag); + + /** + * Return the state of the "CanRestartFromConsole" flag + * + * @returns "CanRestartFromConsole" flag for the server + */ + public boolean canRestartFromConsole(); + + + /** + * Set the URL to be used after the restart. Some configuration changes, like change + * or port or SSL setting, will change server URL. In such cases postRestartURL must be + * set to the new URL + * + * @param url Server URL to be used after the restart + */ + public void setPostRestartURL(String url); + + + /** + * Return the post restart url if set + * + * @returns post restart URL or null + */ + public String getPostRestartURL(); + + + /** + * Set the state of the "ServerShutdown" flag + * The Flag is used to indicate if the server has been shutdown. That means that no + * CGI can be sent to the server + * + * @param flag true=can restart, false=can not need restart + */ + public void setServerShutdown(boolean flag); + + /** + * Return the state of the "ServerShutdown" flag + * + * @returns "CanRestartFromConsole" flag for the server + */ + public boolean isServerShutdown(); + + + +} diff --git a/src/com/netscape/management/admserv/panel/LoggingConfigPanel.java b/src/com/netscape/management/admserv/panel/LoggingConfigPanel.java new file mode 100644 index 0000000..2607911 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/LoggingConfigPanel.java @@ -0,0 +1,189 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.awt.*; +import javax.swing.*; +import javax.swing.event.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.nmclf.SuiConstants; + +/** + * + * @version 0.1 11/23/97 + * @author miodrag@netscape.com + */ +public class LoggingConfigPanel extends PluginConfigPanel { + + IConfigDataModel _configData; + + static ResourceSet _resource; + static String _i18nLogFile, _i18nErrorLogGroupbox, + _i18nAccessLogGroupbox; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nLogFile = _resource.getString("logging","LogFile"); + _i18nAccessLogGroupbox = _resource.getString("logging","AccessLogGroupbox"); + _i18nErrorLogGroupbox = _resource.getString("logging","ErrorLogGroupbox"); + } + + Help _help; + + public static final int topInset = + SuiConstants.SEPARATED_COMPONENT_SPACE; + public static final int rghtColInset = SuiConstants.COMPONENT_SPACE; + + JLabel _lblAccessFile, _lblErrorFile; + JTextField _txtAccessFile, _txtErrorFile; + + + public LoggingConfigPanel(String title, ConsoleInfo consoleInfo) { + super(title); + _configData = new CGILoggingSetup(consoleInfo); + + setLayout(new BorderLayout()); + add(makeConfigPanel(), BorderLayout.NORTH); + _help = new Help(_resource); + } + + public void showHelp() { + _help.contextHelp("loggingHelp"); + } + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) { + _configData = data; + if (_configData.isLoaded()) { + setPanelContent(_configData); + } + } + + public void initialize() throws ConfigPanelException { + try { + if (!_configData.isLoaded()) { + _configData.load(); + } + setPanelContent(_configData); + } catch (ConfigPanelException e) { + throw e; + } + } + + public void resetContent() { + setPanelContent(_configData); + } + + public void applyChanges() throws ValidationException { + try { + getPanelContent(_configData); + } catch (ValidationException e) { + throw e; + } + } + + public void registerEditComponents(EditMonitor editMonitor) { + editMonitor.monitor(_txtAccessFile); + editMonitor.monitor(_txtErrorFile); + } + + public void setPanelContent(IConfigDataModel data) { + String value; + value = (String) data.getAttribute(AttrNames.CONFIG_ACCESSLOG); + _txtAccessFile.setText(value == null ? "" : value); + + value = (String) data.getAttribute(AttrNames.CONFIG_ERRORLOG); + _txtErrorFile.setText(value == null ? "" : value); + } + + public void getPanelContent(IConfigDataModel data) + throws ValidationException { + try { + data.setAttribute(AttrNames.CONFIG_ACCESSLOG, + _txtAccessFile.getText()); + data.setAttribute(AttrNames.CONFIG_ERRORLOG, + _txtErrorFile.getText()); + } catch (ValidationException e) { + throw e; + } + } + + + private JPanel makeConfigPanel() { + + JPanel p = new JPanel(); + GBC gbc = new GBC(); + GridBagLayout gbl; + JPanel ctrlGroup; + + p.setLayout(gbl = new GridBagLayout()); + + _lblAccessFile = new JLabel(_i18nLogFile); + _txtAccessFile = new SingleByteTextField(16); // 324429 + + //gbc.setInsets(0,leftColInset,0,0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(createLogGroup(_i18nAccessLogGroupbox, _lblAccessFile, + _txtAccessFile), gbc); + + _lblErrorFile = new JLabel(_i18nLogFile); + _txtErrorFile = new SingleByteTextField(16); // 324429 + + //gbc.setInsets(0,leftColInset,0,0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(createLogGroup(_i18nErrorLogGroupbox, _lblErrorFile, + _txtErrorFile), gbc); + + return p; + } + + private JPanel createLogGroup(String groupTitle, JLabel lbl, + JTextField txt) { + GridBagLayout gbl; + GBC gbc = new GBC(); + JPanel group = new JPanel(gbl = new GridBagLayout()); + group.setBorder(BaseConfigPanel.createGroupBorder(groupTitle)); + + lbl.setFont(BaseConfigPanel.getLabelFont()); + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.WEST, //anchor + GBC.NONE); //fill + group.add(lbl, gbc); + + gbc.setInsets(0, rghtColInset, 0, 0); + gbc.setGrid(1, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(txt, gbc); + + return group; + } +} diff --git a/src/com/netscape/management/admserv/panel/NetworkConfigPanel.java b/src/com/netscape/management/admserv/panel/NetworkConfigPanel.java new file mode 100644 index 0000000..e9764f8 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/NetworkConfigPanel.java @@ -0,0 +1,733 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.border.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.nmclf.SuiConstants; + +/** + * + * @version 0.1 11/23/97 + * @author miodrag@netscape.com + */ +public class NetworkConfigPanel extends PluginConfigPanel implements SuiConstants { + + IConfigDataModel _configData; + private boolean _unixServer; + + static ResourceSet _resource; + static String _i18nProcessGroupbox, _i18nIPAddr, _i18nHost, + _i18nPort, _i18nServerUID, _i18nMsgBadPortFormat; + static String _i18nConnectGroupbox, _i18nHostNameFilter, + _i18nIPAddrFilter, _i18nEditHostDialog, _i18nEditIPAddrDialog; + static String _i18nMsgEnterHost, _i18nMsgCanUseWildcards, + _i18nMsgEnterIPAddr, _i18nHostFormat, _i18nIPAddrFormat, + _i18nAddHostDialog, _i18nAddIPAddrDialog; + static String _i18nPortRange; + static String _i18nFilterChoice, _i18nIPAddressToolTip, _i18nPortToolTip, _i18nUIDToolTip; + static String _i18nHostListToolTip, _i18nIPListToolTip; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nProcessGroupbox = _resource.getString("network","ProcessGroupbox"); + _i18nPort = _resource.getString("network","Port"); + _i18nHost = _resource.getString("network","Host"); + _i18nIPAddr = _resource.getString("network","IPAddr"); + _i18nMsgCanUseWildcards = _resource.getString("network","MsgCanUseWildcards"); + _i18nServerUID = _resource.getString("network","ServerUID"); + _i18nMsgBadPortFormat = _resource.getString("network","MsgBadPortFormat"); + _i18nConnectGroupbox = _resource.getString("network","ConnectGroupbox"); + _i18nHostNameFilter = _resource.getString("network","HostNameFilter"); + _i18nIPAddrFilter = _resource.getString("network","IPAddrFilter"); + _i18nEditHostDialog = _resource.getString("network","EditHostDialog"); + _i18nEditIPAddrDialog = _resource.getString("network","EditIPAddrDialog"); + _i18nMsgEnterHost = _resource.getString("network","MsgEnterHost"); + _i18nMsgEnterIPAddr = _resource.getString("network","MsgEnterIPAddr"); + _i18nHostFormat = _resource.getString("network","HostFormat"); + _i18nIPAddrFormat = _resource.getString("network","IPAddrFormat"); + _i18nAddHostDialog = _resource.getString("network", "AddHostDialog"); + _i18nAddIPAddrDialog = _resource.getString("network", "AddIPAddrDialog"); + _i18nPortRange = _resource.getString("common","PortRange"); + _i18nFilterChoice = _resource.getString("network","ToolTipFilterChoice"); + _i18nIPAddressToolTip = _resource.getString("network","IPAddressToolTip"); + _i18nPortToolTip = _resource.getString("network","PortToolTip"); + _i18nUIDToolTip = _resource.getString("network","serverUIDToolTip"); + _i18nHostListToolTip = _resource.getString("network","HostListToolTip"); + _i18nIPListToolTip = _resource.getString("network","IPListToolTip"); + + } + + Help _help; + + // Panel Controls + JLabel _lblPort, _lblAddress, _lblServerUID; + JTextField _txtPort, _txtAddress, _txtServerUID; + FilterEditList _hostList, _ipList; + + public NetworkConfigPanel(String title, IConfigDataModel data, + boolean unixServer) { + super(title); + _configData = data; + _unixServer = unixServer; + + setLayout(new BorderLayout()); + add(makeConfigPanel(), BorderLayout.NORTH); + _help = new Help(_resource); + } + + public void showHelp() { + _help.contextHelp("networkHelp"); + } + + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) { + _configData = data; + if (_configData.isLoaded()) { + setPanelContent(_configData); + } + } + + public void initialize() throws RemoteRequestException { + if (!_configData.isLoaded()) + _configData.load(); + + if (_configData instanceof CGIDataModel) { + ((CGIDataModel)_configData).setDialogParent(getParent()); + } else if (_configData instanceof CGIAggregateDataModel) { + ((CGIAggregateDataModel)_configData).setDialogParent( + getParent()); + } + setPanelContent(_configData); + } + + public void resetContent() { + setPanelContent(_configData); + } + + public void applyChanges() throws ValidationException { + try { + validateData(); + getPanelContent(_configData); + } catch (ValidationException e) { + throw e; + } + } + + public void validateData() throws ValidationException { + try { + int portNum = Integer.parseInt(_txtPort.getText()); + if (portNum < 1 || portNum > 65535) { + throw new ValidationException("",_i18nPortRange); + } + } catch (Exception e) { + throw new ValidationException(_i18nPort + + _txtPort.getText(), _i18nPortRange); + } + validateIPAddress(getAddress()); + } + + public void registerEditComponents(EditMonitor editMonitor) { + editMonitor.monitor(_txtPort); + editMonitor.monitor(_txtAddress); + if (_unixServer) { + editMonitor.monitor(_txtServerUID); + } + _hostList.addListDataListener(editMonitor); + _ipList.addListDataListener(editMonitor); + } + + public void validateIPAddress(String ipAddr) + throws ValidationException { + if (ipAddr.length() == 0) { + return; // no ip address means listen on all interfaces + } + + StringTokenizer checker = new StringTokenizer(ipAddr, "."); + if (checker.countTokens() != 4 || ipAddr.startsWith(".") || + ipAddr.endsWith(".")) { + throw new ValidationException("", + NetworkConfigPanel._i18nMsgEnterIPAddr); + } + while (checker.hasMoreElements()) { + String ipAddrComponent = (String) checker.nextElement(); + try { + //parseInt will throw exception if bad numner format + int i = Integer.parseInt(ipAddrComponent); + } catch (Exception e) { + throw new ValidationException("", + NetworkConfigPanel._i18nMsgEnterIPAddr); + } + } + } + + public void setPanelContent(IConfigDataModel data) { + String port = data.getAttribute(AttrNames.CONFIG_SERVERPORT); + setPort(port); + _lblPort.setText(_i18nPort); + _txtPort.setEnabled(true); + + String address = data.getAttribute(AttrNames.CONFIG_SERVERADDRESS); + setAddress(address); + _lblAddress.setText(_i18nIPAddr); + _txtAddress.setEnabled(true); + + if (_unixServer) { + setServerUID(data.getAttribute(AttrNames.CONFIG_USER)); + } + + _hostList.setList( CGIServerSetup.parseFilterList( + (String) data.getAttribute(AttrNames.CONFIG_HOSTS))); + _ipList.setList( CGIServerSetup.parseFilterList( + (String) data.getAttribute(AttrNames.CONFIG_ADDRESSES))); + } + + public void getPanelContent(IConfigDataModel data) + throws ValidationException { + try { + data.setAttribute(AttrNames.CONFIG_SERVERPORT, + _txtPort.getText()); + + data.setAttribute(AttrNames.CONFIG_SERVERADDRESS, + getAddress()); + + data.setAttribute(AttrNames.CONFIG_HOSTS, + CGIServerSetup.encodeFilterList(_hostList.getList())); + data.setAttribute(AttrNames.CONFIG_ADDRESSES, + CGIServerSetup.encodeFilterList(_ipList.getList())); + if (_unixServer) { + data.setAttribute(AttrNames.CONFIG_USER, getServerUID()); + } + } catch (ValidationException e) { + throw e; + } + } + + /** + * Override BaseEditPanel.makeConfigPanel() to provide a custom panel, + * called by baseEditPanel constructor + */ + protected JComponent makeConfigPanel() { + JPanel p = new JPanel(); + GBC gbc = new GBC(); + GridBagLayout gbl; + JPanel ctrlGroup; + + p.setLayout(gbl = new GridBagLayout()); + + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(createProcessGroup(), gbc); + + gbc.setInsets(SEPARATED_COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(1.0, 1.0, GBC.WEST, //anchor + GBC.BOTH); //fill + p.add(createConnectGroup(), gbc); + + return p; + } + + private JPanel createProcessGroup() { + GridBagLayout gbl; + GBC gbc = new GBC(); + JPanel group = new JPanel(gbl = new GridBagLayout()); + group.setBorder( + BaseConfigPanel.createGroupBorder(_i18nProcessGroupbox)); + + _lblPort = new JLabel(_i18nPort); + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, //anchor + GBC.NONE); //fill + group.add(_lblPort, gbc); + + _txtPort = new JTextField(6); + _txtPort.setDocument(FilteredInputDocument.allowDigitsOnly()); + gbc.setInsets(0, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(_txtPort, gbc); + _lblPort.setLabelFor(_txtPort); + _lblPort.setToolTipText(_i18nPortToolTip); + _txtPort.setToolTipText(_i18nPortToolTip); + + JLabel label = new JLabel(""); // spacer + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(2, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(label, gbc); + + _lblAddress = new JLabel(_i18nIPAddr); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + group.add(_lblAddress, gbc); + + _txtAddress = new JTextField(16); + _txtAddress.setDocument( + FilteredInputDocument.allowIPAddressOnly()); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 1, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(_txtAddress, gbc); + _lblAddress.setLabelFor(_txtAddress); + _lblAddress.setToolTipText(_i18nIPAddressToolTip); + _txtAddress.setToolTipText(_i18nIPAddressToolTip); + + // Add ServerUID only if UNIX server + if (!_unixServer) + return group; + + _lblServerUID = new JLabel(_i18nServerUID); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 2, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + group.add(_lblServerUID, gbc); + + _txtServerUID = new JTextField(16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 2, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + group.add(_txtServerUID, gbc); + _lblServerUID.setLabelFor(_txtServerUID); + _lblServerUID.setToolTipText(_i18nUIDToolTip); + _txtServerUID.setToolTipText(_i18nUIDToolTip); + + return group; + } + + JComboBox _filterChoice; + JPanel _filterList; + ActionListener _filterChoiceListener = new ActionListener () { + public void actionPerformed(ActionEvent e) { + if ((String)_filterChoice.getSelectedItem() == + _i18nHostNameFilter) { + _card.show(_filterList, "hostList"); + } else { + _card.show(_filterList, "ipList"); + } + } + }; + + CardLayout _card; + + private JPanel createConnectGroup() { + JPanel p = new JPanel(new BorderLayout()); + p.setBorder( + BaseConfigPanel.createGroupBorder(_i18nConnectGroupbox)); + + _filterChoice = new JComboBox(); + _filterChoice.addItem(_i18nHostNameFilter); + _filterChoice.addItem(_i18nIPAddrFilter); + _filterChoice.addActionListener(_filterChoiceListener); + _filterChoice.setToolTipText(_i18nFilterChoice); + _filterList = new JPanel(_card = new CardLayout()); + _hostList = new HostEditList(); + _hostList.getAccessibleContext().setAccessibleDescription(_i18nHostListToolTip); + _hostList.setToolTipText(_i18nHostListToolTip); + _ipList = new IPAddrEditList(); + _ipList.getAccessibleContext().setAccessibleDescription(_i18nIPListToolTip); + _ipList.setToolTipText(_i18nIPListToolTip); + _filterList.add(_hostList, "hostList"); + _filterList.add(_ipList, "ipList"); + + JPanel p1 = new JPanel (new BorderLayout()); + p1.add(_filterChoice, BorderLayout.WEST); + p.add(p1, BorderLayout.NORTH); + p.add(_filterList, BorderLayout.CENTER); + + return p; + } + + + private JPanel createHostRestrictGroup() { + JPanel group = new JPanel(new BorderLayout()); + group.add(_hostList = new HostEditList(), BorderLayout.NORTH); + return group; + } + + private JPanel createIPRestrictGroup() { + JPanel group = new JPanel(new BorderLayout()); + group.add(_ipList = new IPAddrEditList(), BorderLayout.NORTH); + return group; + } + + + public void setPort(String port) { + _txtPort.setText((port != null) ? port : ""); + } + + public String getPort() { + String port = _txtPort.getText(); + return port; + } + + public void setAddress(String addr) { + _txtAddress.setText((addr != null) ? addr : ""); + } + + public String getAddress() { + String addr = _txtAddress.getText(); + return addr; + } + + + public void setServerUID(String account) { + _txtServerUID.setText((account != null) ? account : ""); + if (account != null) { + _txtServerUID.setEnabled(account.equals("root")); + } + } + + public String getServerUID() { + String account = _txtServerUID.getText(); + return account; + } +} + +/** + * Host Edit List + */ +class HostEditList extends FilterEditList { + + static String _i18nEditHost, _i18nAddHost, _i18nRemoveHost; + static { + _i18nEditHost = _resource.getString("network","EditHostToolTip"); + _i18nAddHost = _resource.getString("network","AddHostToolTip"); + _i18nRemoveHost = _resource.getString("network","RemoveHostToolTip"); + } + + public JPanel getEditPanel() { + _editPanel = new FilterEditPanel(NetworkConfigPanel._i18nHost, + NetworkConfigPanel._i18nHostFormat); + setEditPanelInitalFocusComponent(_editPanel.getTextField()); + setEditPanelCommitOnEnterComponents( + new JTextField[]{_editPanel.getTextField()}); + return _editPanel; + } + + public String getEditTitle() { + return NetworkConfigPanel._i18nEditHostDialog; + } + public String getAddTitle() { + return NetworkConfigPanel._i18nAddHostDialog; + } + + public String getEditToolTip() { + return _i18nEditHost; + } + + public String getAddToolTip() { + return _i18nAddHost; + } + + public String getRemoveToolTip() { + return _i18nRemoveHost; + } + + public ResourceSet getHelpResourceSet() { + return NetworkConfigPanel._resource; + }; + public String getHelpToken() { + return "editHostHelp"; + } + + public void validateEdit() throws ValidationException { + String host = _editPanel.getItem(); + if (host.length() == 0) { + throw new ValidationException("", + NetworkConfigPanel._i18nMsgEnterHost); + } else { + for (int i = 0; i < host.length(); i++) { + char c = host.charAt(i); + if (c > 0x007f) { + throw new ValidationException("", + NetworkConfigPanel._i18nMsgEnterHost); + } + } + } + } +} + +/** + * IP Address Edit List + */ +class IPAddrEditList extends FilterEditList { + + static String _i18nEditIP, _i18nAddIP, _i18nRemoveIP; + static { + _i18nEditIP = _resource.getString("network","EditIPToolTip"); + _i18nAddIP = _resource.getString("network","AddIPToolTip"); + _i18nRemoveIP = _resource.getString("network","RemoveIPToolTip"); + } + + public JPanel getEditPanel() { + _editPanel = new FilterEditPanel(NetworkConfigPanel._i18nIPAddr, + NetworkConfigPanel._i18nIPAddrFormat); + _editPanel.getTextField().setDocument( + new FilteredInputDocument("1234567890.*")); + setEditPanelInitalFocusComponent(_editPanel.getTextField()); + setEditPanelCommitOnEnterComponents( + new JTextField[]{_editPanel.getTextField()}); + return _editPanel; + } + + public String getEditTitle() { + return NetworkConfigPanel._i18nEditIPAddrDialog; + } + public String getAddTitle() { + return NetworkConfigPanel._i18nAddIPAddrDialog; + } + + public String getEditToolTip() { + return _i18nEditIP; + } + + public String getAddToolTip() { + return _i18nAddIP; + } + + public String getRemoveToolTip() { + return _i18nRemoveIP; + } + + public ResourceSet getHelpResourceSet() { + return NetworkConfigPanel._resource; + }; + public String getHelpToken() { + return "editIPAddrHelp"; + } + + public void validateEdit() throws ValidationException { + String ipAddr = _editPanel.getItem(); + if (ipAddr.length() == 0) { + String errmsg = NetworkConfigPanel._i18nMsgEnterIPAddr + "\n" + + NetworkConfigPanel._i18nMsgCanUseWildcards; + throw new ValidationException("", errmsg); + } + + if (ipAddr.equals("*")) + return ; + + StringTokenizer checker = new StringTokenizer(ipAddr, "."); + if (checker.countTokens() != 4 || ipAddr.startsWith(".") || + ipAddr.endsWith(".")) { + String errmsg = NetworkConfigPanel._i18nMsgEnterIPAddr + "\n" + + NetworkConfigPanel._i18nMsgCanUseWildcards; + throw new ValidationException("", errmsg); + } + while (checker.hasMoreElements()) { + String ipAddrComponent = (String) checker.nextElement(); + try { + if (!ipAddrComponent.equals("*")) { + //parseInt will throw exception if bad numner format + int i = Integer.parseInt(ipAddrComponent); + } + } catch (Exception e) { + String errmsg = NetworkConfigPanel._i18nMsgEnterIPAddr + + "\n" + NetworkConfigPanel._i18nMsgCanUseWildcards; + throw new ValidationException("", errmsg); + } + } + } +} + +/** + * A custom component that enables element in the list to be edited: + * add, edit, remove + * Common class for both Host and Ip Addr edit lists + */ +abstract class FilterEditList extends EditableList { + + FilterEditPanel _editPanel; + Vector _items; + + public FilterEditList() { + //setBorder(new EmptyBorder(10,0,0,0)); + } + + private int findItem(String name) { + for (int i = 0; i < _items.size(); i++) { + String host = (String)_items.elementAt(i); + if (host.equals(name)) { + return i; + } + } + return -1; + } + + /** + * No custom panel + */ + public JPanel getDetailsPanel() { + return null; + } + public String getDetailsTitle() { + return null; + } + + + /** + * A method called to populate the contents of edit panel. + * Paremeter item is null for ADD operation. A + * non-null string is passed for EDIT operation + */ + public void setEditPanelParameters(String item) { + if (item != null) { + _editPanel.setItem(item); + } else { + _editPanel.setItem(""); + } + } + + /** + * A method called to craete a new item. The item parameters should + * be read from the custom edit panel + */ + public void createItem(String name) { + _items.addElement(new String(name)); + } + + + /** + * A method called to update an item. The item parameters should + * be read from the custom edit panel + */ + public void updateItem(String name, boolean isRenamed) { + int idx = findItem(name); + if (idx >= 0) { + _items.setElementAt(new String(_editPanel.getItem()), idx); + } else { + Debug.println("ERROR: Item not found: " + name); + } + } + + /** + * A method called to remove an item. + */ + public void removeItem(String name) { + int idx = findItem(name); + if (idx >= 0) { + _items.removeElementAt(idx); + } else { + Debug.println("ERROR: Not found: " + name); + } + } + + /** + * A method called when an item is selected + */ + public void selectItem(String item) {} + + /** + * A method called to read the item from the edit panel + */ + public String getEditPanelItem() { + return _editPanel.getItem(); + } + + public void setList(Vector v) { + super.setList(_items = v); + } + + public Vector getList() { + return _items; + } + + +} + +/** + * Host Filter Edit Panel + */ +class FilterEditPanel extends JPanel implements SuiConstants { + String _cmd = "", _item = ""; + JTextField _txtItem; + String _i18nItemLabel, _i18nItemDescription; + + FilterEditPanel(String itemLabel, String itemDescription) { + _i18nItemLabel = itemLabel; + _i18nItemDescription = itemDescription; + createLayout(); + } + + private JPanel createLayout() { + GBC gbc = new GBC(); + setLayout(new GridBagLayout()); + + //JLabel label = new JLabel(_i18nItemDescription); + //label.setUI(new com.netscape.page.MultilineLabelUI()); + MultilineLabel label = new MultilineLabel(_i18nItemDescription); + gbc.setGrid(0, 0, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + add(label, gbc); + + JLabel lblItem = new JLabel(_i18nItemLabel); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + add(lblItem, gbc); + + _txtItem = new JTextField(_item, 16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, //anchor + GBC.HORIZONTAL); //fill + add(_txtItem, gbc); + lblItem.setLabelFor(_txtItem); + + return this; + } + + public String getItem() { + return _item = _txtItem.getText(); + } + + public void setItem(String item) { + _txtItem.setText(_item = item); + } + + public JTextField getTextField() { + return _txtItem; + } +} + diff --git a/src/com/netscape/management/admserv/panel/RestartOperation.java b/src/com/netscape/management/admserv/panel/RestartOperation.java new file mode 100644 index 0000000..e4054af --- /dev/null +++ b/src/com/netscape/management/admserv/panel/RestartOperation.java @@ -0,0 +1,264 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.comm.CommRecord; +import com.netscape.management.client.comm.CommManager; +import java.io.ByteArrayInputStream; + +public class RestartOperation extends AdminOperation { + protected static int STATE_REQ_RESTART = 0; + protected static int STATE_GET_NEWPID = 1; + + protected int _oldPID = -1, _newPID = -1; + protected int _state; + protected String _taskArguments = "op=restart"; + protected IRestartControl _restartControl; + + String _i18nSendRequest = _resource.getString("restart","SendRequest"); + String _i18nAccepted = _resource.getString("restart","Accepted"); + String _i18nWait = _resource.getString("restart","Wait"); + String _i18nDone = _resource.getString("restart","Done"); + String _i18nStopped = _resource.getString("restart","Stopped"); + + public RestartOperation(ConsoleInfo consoleInfo) { + super(consoleInfo, "admin-serv/tasks/Operation/Restart"); + _restartControl = + (IRestartControl)_consoleInfo.get(IRestartControl.ID); + createActionPanel(/*multiLined=*/true); + } + + // Override createTask to add arguments and use custom AdmTask + protected void createTask(ConsoleInfo ci, + String adminURL) throws RemoteRequestException { + try { + _task = new TimeoutAdmTask(new URL(adminURL), + ci.getAuthenticationDN(), + ci.getAuthenticationPassword()); + } catch (MalformedURLException e) { + Debug.println(""+e); + throw new RemoteRequestException(e); + } + + _task.setArguments(_taskArguments); + } + + + /** + * Issue restart request and record pid returned in the response. Afterwards, poll + * for pid until new pid is detected + */ + public void performOperationalTask(ConsoleInfo ci, + String taskURL) throws RemoteRequestException { + _state = STATE_REQ_RESTART; + _oldPID = _newPID = -1; + _taskArguments = "op=restart"; + _actionPanel.setStatusText(_i18nSendRequest); + super.performOperationalTask(ci, taskURL); + _actionPanel.setStatusText(_i18nAccepted); + + // Read oldPID from the CGI result + if (_task != null && _task.getResult() != null) { + String pid = (String)_task.getResult().get("pid"); + try { + _oldPID = Integer.parseInt(pid); + } catch (Exception e) {} + Debug.println("restart pid =" + pid); + } + + if (_oldPID == -1) { + throw new RemoteRequestException(taskURL, "No server PID in CGI response,\nRestart CGI needs to be upgraded to the latest version"); + } + + // Send the message to the Server Object that the restart is not needed any more + if (_restartControl != null) { + _restartControl.setNeedsAutoRestart(false); + } + + // set new parameters for polling the server PID + long t0 = System.currentTimeMillis(); + boolean stopDetected = false; + + _state = STATE_GET_NEWPID; + _taskArguments = "op=getpid"; // must be set before the call to createTask + createTask(ci, ci.getAdminURL() + _taskURL); + ((TimeoutAdmTask)_task).setMaxWaitInterval(5000); + + _actionPanel.setStatusText(_i18nWait); + _actionPanel.setStatusTextSameLIne("\n"); + + // Poll pid, wait until server switched to a new PID + while (_newPID == -1 || _newPID == _oldPID) { + + // Sleep 3 sec between consecutive poll requests + try { + Thread.currentThread().sleep(3000); + } catch (Exception e) {} + + Debug.println("Exec " + ((TimeoutAdmTask)_task).getURL()); + _task.exec(); + processAdmTaskStatus(taskURL); + + // Try frist to detect when the server is stopped + if (!stopDetected && _task != null && _task.getStatus() == -1 && + _task.getException() != null && _task.getException() + instanceof java.net.ConnectException) { + stopDetected = true; + _actionPanel.setStatusTextSameLIne("\n" + + _i18nStopped + "\n"); + + // If port number has changed we need to use new adminURL for poll requests + String postRestartURL = (_restartControl == null) ? null : + _restartControl.getPostRestartURL(); + if (postRestartURL != null) { + Debug.println("post restart URL = " + postRestartURL); + _consoleInfo.setAdminURL(postRestartURL); + createTask(ci, postRestartURL + _taskURL); + ((TimeoutAdmTask)_task).setMaxWaitInterval(5000); + } + } + + // Read new PID from the CGI result + if (_task != null && _task.getStatus() == 0 && + _task.getResult() != null) { + String pid = (String)_task.getResult().get("pid"); + try { + _newPID = Integer.parseInt(pid); + } catch (Exception e) {} + Debug.println("getpid pid =" + pid + " old pid = " + + _oldPID); + } + _actionPanel.setStatusTextSameLIne("*"); + + // Start a new line if after 90 sec restart not detected + if ((System.currentTimeMillis() - t0) > 90000) { + t0 = System.currentTimeMillis(); + _actionPanel.setStatusTextSameLIne("\n"); + } + } + _actionPanel.setStatusText(_i18nDone + "\n"); + + Debug.println("Operation time = " + + (System.currentTimeMillis() - t0) / 1000.); + + } + + + // Override processAdmTaskStatus() to handle errors during pid polling + public void processAdmTaskStatus(String url) + throws RemoteRequestException { + Debug.println("status="+_task.getStatus() + " ex=" + + _task.getException() + " result="+_task.getResult()); + int status = _task.getStatus(); + + if (_state == STATE_GET_NEWPID) { + if (status == -1) { + // We can tolerate this errors as the server might be just going up or down + Debug.println("getpid request error " + + _task.getException()); + return; + } else if (status == -2) { + Debug.println("getpid request timedout"); + // Timeout occured + return; + } + } + super.processAdmTaskStatus(url); + } +} + + +class TimeoutAdmTask extends AdmTask { + + private long _maxWait; + private CommRecord _commRecord; + + public TimeoutAdmTask(URL url, String userID, String userPassword) { + super(url, userID, userPassword); + } + + public void setMaxWaitInterval(long maxWait) { + _maxWait = maxWait; + } + + + public String getURL() { + return _adminURL.toString(); + } + + // Override waitForFinish() to limit wait time + public synchronized void waitForFinish() { + while (!_finished) { + try { + if (_maxWait == 0) { + wait(); + } else { + long t0 = System.currentTimeMillis(); + Debug.println("wait " + _maxWait); + wait(_maxWait); + if (!_finished) { + _error = -2; //REQUEST_TIMEDOUT; + if (_response != null) + _response.clear(); + _httpManager.terminate(_commRecord); + return; + } + } + } catch (Exception e) {} + } + } + + // Override exec() to record CommRecord. Need it for terminate() on httpmanager + public int exec() { + _responseString = new StringBuffer(); + ByteArrayInputStream data = null; + try { + Debug.println("exec " + _adminURL + " args:"+ _argumentString); + + if (_response != null) + _response.clear(); + _finished = false; + _exception = null; + _error = 0; + + data = new ByteArrayInputStream(_argumentString.getBytes()); + if (data == null) { + _commRecord = _httpManager.post(_adminURL, this, null, null, + 0, CommManager.FORCE_BASIC_AUTH); + } else { + _commRecord = _httpManager.post(_adminURL, this, null, data, + data.available(), CommManager.FORCE_BASIC_AUTH); + } + + waitForFinish(); + return(0); + } catch (Exception e) { + Debug.println(""+e); + _exception = e; + _error = -1; + return -1; + } + } +} diff --git a/src/com/netscape/management/admserv/panel/SNMPCommunityPanel.java b/src/com/netscape/management/admserv/panel/SNMPCommunityPanel.java new file mode 100644 index 0000000..ef79b76 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/SNMPCommunityPanel.java @@ -0,0 +1,525 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.border.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.nmclf.SuiConstants; + +/** + * + * @version 0.1 11/23/97 + * @author miodrag@netscape.com + */ +public class SNMPCommunityPanel extends PluginConfigPanel { + + IConfigDataModel _configData; + + static ResourceSet _resource; + static String _i18nDescription, _i18nDetailsGroupbox; + static String _i18nOperationsAll, _i18nOperationsGET, + _i18nOperationsSET; + static String _i18nDetailName, _i18nDetailOperations; + static String _i18nEditDialogCommunity, _i18nEditDialogTitle, + _i18nAddDialogTitle; + static String _i18nMsgEnterCommunity, _i18nEditDialogOperationsGroupbox; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nDescription = _resource.getString("snmpcom","Description"); + _i18nDetailsGroupbox = _resource.getString("snmpcom","DetailsGroupbox"); + _i18nOperationsAll = _resource.getString("snmpcom","OperationsAll"); + _i18nOperationsGET = _resource.getString("snmpcom","OperationsGET"); + _i18nOperationsSET = _resource.getString("snmpcom","OperationsSET"); + _i18nDetailName = _resource.getString("snmpcom","DetailName"); + _i18nDetailOperations = _resource.getString("snmpcom","DetailOperations"); + _i18nEditDialogCommunity = _resource.getString("snmpcom","EditDialogCommunity"); + _i18nEditDialogTitle = _resource.getString("snmpcom","EditDialogTitle"); + _i18nAddDialogTitle = _resource.getString("snmpcom","AddDialogTitle"); + _i18nEditDialogOperationsGroupbox = + _resource.getString("snmpcom","EditDialogOperationsGroupbox"); + _i18nMsgEnterCommunity = _resource.getString("snmpcom","MsgEnterCommunity"); + + } + + Help _help; + + // Panel Controls + JLabel _lblDescription; + CommunityList _communityList; + Vector _communities = new Vector(); + + public SNMPCommunityPanel(String title, IConfigDataModel data) { + super(title); + _configData = data; + + setLayout(new BorderLayout()); + add(makePanel(), BorderLayout.NORTH); + _help = new Help(_resource); + } + + public void showHelp() { + _help.contextHelp("SNMPCommunityHelp"); + } + + + public void initialize() throws ConfigPanelException { + setPanelContent(_configData); + } + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) + throws ValidationException { + _configData = data; + if (_configData.isLoaded()) { + setPanelContent(_configData); + } + } + + public void resetContent() throws ConfigPanelException { + setPanelContent(_configData); + } + + public void applyChanges() throws ValidationException { + getPanelContent(_configData); + } + + public void registerEditComponents(EditMonitor editMonitor) { + _communityList.addListDataListener(editMonitor); + } + + public void setPanelContent(IConfigDataModel data) + throws ValidationException { + String value = data.getAttribute(AttrNames.SNMP_COMMUNITIES); + _communities = CGISNMPSetup.stringToCommunityVector(value); + _communityList.setCommunities(_communities); + } + + public void getPanelContent(IConfigDataModel data) + throws ValidationException { + String value = CGISNMPSetup.communityVectorToString(_communities); + data.setAttribute(AttrNames.SNMP_COMMUNITIES, value); + } + + /** + * + */ + protected JComponent makePanel() { + JPanel p = new JPanel(); + GBC gbc = new GBC(); + GridBagLayout gbl; + JPanel ctrlGroup; + + p.setLayout(gbl = new GridBagLayout()); + + JLabel lbl = new JLabel(_i18nDescription); + gbc.setInsets(10, 0, 10, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(lbl, gbc); + + _communityList = new CommunityList(_communities); + //gbc.setInsets(topInset,leftColInset,0,0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(_communityList, gbc); + + return p; + } +} + +/** + * A custom component that enables element in the list to be edited: + * add, edit, remove + */ +class CommunityList extends EditableList { + + CommunityEditPanel _editPanel; + JPanel _detailsPanel; + JLabel _lblDetailsName, _lblDetailsOperation; + Vector _communities; + + String _cmdSet = "SET", _cmdGet = "GET", _cmdAll = "ALL"; + + static String _i18nEditCommunity, _i18nAddCommunity, _i18nRemoveCommunity; + + static { + _i18nEditCommunity = _resource.getString("snmpcom","EditCommunityToolTip"); + _i18nAddCommunity = _resource.getString("snmpcom","AddCommunityToolTip"); + _i18nRemoveCommunity = _resource.getString("snmpcom","RemoveCommunityToolTip"); + } + + public CommunityList(Vector communities) { + setCommunities(communities); + } + + public void setCommunities(Vector communities) { + _communities = communities; + setList(getCommunityNames(_communities)); + } + + Vector getCommunityNames(Vector entryList) { + Vector v = new Vector(entryList.size()); + for (int i = 0; i < entryList.size(); i++) { + Hashtable entry = (Hashtable) entryList.elementAt(i); + v.addElement(entry.get(CGISNMPSetup.COMMUNITY_NAME)); + } + return v; + } + + public JPanel getEditPanel() { + _editPanel = new CommunityEditPanel(); + JTextField[] txtComponents = _editPanel.getTextComponents(); + setEditPanelInitalFocusComponent(txtComponents[0]); + setEditPanelCommitOnEnterComponents(txtComponents); + return _editPanel; + + } + + public String getEditTitle() { + return SNMPCommunityPanel._i18nEditDialogTitle; + } + + public String getAddTitle() { + return SNMPCommunityPanel._i18nAddDialogTitle; + } + + public String getEditToolTip() { + return _i18nEditCommunity; + } + + public String getAddToolTip() { + return _i18nAddCommunity; + } + + public String getRemoveToolTip() { + return _i18nRemoveCommunity; + } + + public ResourceSet getHelpResourceSet() { + return SNMPCommunityPanel._resource; + }; + public String getHelpToken() { + return "editSNMPCommunityHelp"; + } + + + public JPanel getDetailsPanel() { + return _detailsPanel = createDetailsPanel(); + } + + public String getDetailsTitle() { + return SNMPCommunityPanel._i18nDetailsGroupbox; + } + + + private JPanel createDetailsPanel() { + JPanel p = new JPanel(new GridBagLayout()); + GBC gbc = new GBC(); + + JLabel lbl = new JLabel(SNMPCommunityPanel._i18nDetailName, + JLabel.LEFT); + //lbl.setFont(BaseConfigPanel.getLabelFont()); + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor + GBC.BOTH); //fill + p.add(lbl, gbc); + + _lblDetailsName = new JLabel(" ", JLabel.LEFT); + gbc.setInsets(0, 10, 0, 0); + gbc.setGrid(1, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_lblDetailsName, gbc); + + lbl = new JLabel(SNMPCommunityPanel._i18nDetailOperations, + JLabel.LEFT); + //lbl.setFont(BaseConfigPanel.getLabelFont()); + gbc.setInsets(10, 0, 0, 0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + p.add(lbl, gbc); + + _lblDetailsOperation = new JLabel(" ", JLabel.LEFT); + gbc.setInsets(10, 10, 0, 0); + gbc.setGrid(1, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_lblDetailsOperation, gbc); + + return p; + + } + + public void validateEdit() throws ValidationException { + String community = _editPanel.getCommunity(); + if (community.length() == 0) { + throw new ValidationException( + SNMPCommunityPanel._i18nEditDialogCommunity, + SNMPCommunityPanel._i18nMsgEnterCommunity); + } + } + + public void setEditPanelParameters(String item) { + if (item == null) { //add + _editPanel.setCommunity(""); + _editPanel.setOperation(_cmdAll); + } else { //edit + int idx = findCommunity(item); + if (idx >= 0) { + Hashtable entry = (Hashtable)_communities.elementAt(idx); + _editPanel.setCommunity(item); + _editPanel.setOperation( (String) entry.get( + CGISNMPSetup.COMMUNITY_OPERATION)); + } else { + Debug.println("ERROR: Community not found: " + item); + } + } + } + + public String getEditPanelItem() { + return _editPanel.getCommunity(); + } + + + private int findCommunity(String name) { + return CGISNMPSetup.findEntry(_communities, + CGISNMPSetup.COMMUNITY_NAME , name); + } + + public void createItem(String item) { + _communities.addElement( + CGISNMPSetup.createCommunityEntry(new String(item), + new String(_editPanel.getOperation()))); + //dumpData(); + } + + public void removeItem(String item) { + int idx = findCommunity(item); + if (idx >= 0) { + _communities.removeElementAt(idx); + } else { + Debug.println("ERROR: Community not found: " + item); + } + //dumpData(); + } + + public void updateItem(String item, boolean isRenamed) { + int idx = findCommunity(item); + if (idx >= 0) { + Hashtable entry = CGISNMPSetup.createCommunityEntry( + new String(_editPanel.getCommunity()), + new String(_editPanel.getOperation())); + _communities.setElementAt(entry, idx); + } else { + Debug.println("ERROR: Community not found: " + item); + } + //dumpData(); + } + + + private void dumpData() { + if (_communities.size() == 0) { + Debug.println("No entries"); + return; + } + + for (int i = 0; i < _communities.size(); i++) { + Hashtable entry = (Hashtable)_communities.elementAt(i); + String community = + (String) entry.get(CGISNMPSetup.COMMUNITY_NAME); + String operation = + (String) entry.get(CGISNMPSetup.COMMUNITY_OPERATION); + Debug.print(i + "=[" + community + " " + operation + "] "); + } + Debug.println(""); + } + + + public void selectItem(String item) { + + //Debug.println("selectItem " + item); + + if (item == null) { + _lblDetailsName.setText(""); + _lblDetailsOperation.setText(""); + return; + } + + int idx = findCommunity(item); + + if (idx >= 0) { + + Hashtable entry = (Hashtable)_communities.elementAt(idx); + String community = + (String) entry.get(CGISNMPSetup.COMMUNITY_NAME); + String operation = + (String) entry.get(CGISNMPSetup.COMMUNITY_OPERATION); + + //Debug.println("idx=" + idx + " detail =" + name + " " + operation); + + _lblDetailsName.setText(community); + + if (operation.equals(_cmdAll)) { + operation = SNMPCommunityPanel._i18nOperationsAll; + } else if (operation.equals(_cmdGet)) { + operation = SNMPCommunityPanel._i18nOperationsGET; + } else if (operation.equals(_cmdSet)) { + operation = SNMPCommunityPanel._i18nOperationsSET; + } else { + Debug.println("ERROR: Bad perrmissions: " + item); + } + _lblDetailsOperation.setText(operation); + } else { + Thread.currentThread().dumpStack(); + Debug.println("ERROR: Community not found: " + item); + } + } + +} + +/** + * Community Edit Dialog + */ +class CommunityEditPanel extends JPanel implements SuiConstants { + String _community = ""; + JTextField _txtCommunity; + JRadioButton _rbSet, _rbGet, _rbAll; + String _cmdSet = "SET", _cmdGet = "GET", _cmdAll = "ALL"; + + String _operation = _cmdAll; + + public CommunityEditPanel() { + createLayout(); + } + + private Border createGroupBorder(String label) { + TitledBorder border = new TitledBorder(new EtchedBorder(), label); + border.setTitleFont(BaseConfigPanel.getLabelFont()); + return new CompoundBorder(border, new EmptyBorder(0, 6, 0, 0)); + + } + + private void createLayout() { + GBC gbc = new GBC(); + setLayout(new GridBagLayout()); + + JLabel lblCommunity = + new JLabel(SNMPCommunityPanel._i18nEditDialogCommunity); + lblCommunity.setFont(BaseConfigPanel.getLabelFont()); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + add(lblCommunity, gbc); + + _txtCommunity = new JTextField(_community, 16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, //anchor + GBC.HORIZONTAL); //fill + add(_txtCommunity, gbc); + lblCommunity.setLabelFor(_txtCommunity); + + JPanel operationPanel = new JPanel(new GridLayout(1, 0, 0, 5)); + operationPanel.setBorder( createGroupBorder( + SNMPCommunityPanel._i18nEditDialogOperationsGroupbox)); + ButtonGroup radio = new ButtonGroup(); + + _rbAll = new JRadioButton(SNMPCommunityPanel._i18nOperationsAll); + _rbAll.setActionCommand(_cmdAll); + _rbAll.addActionListener(radioListener); + _rbAll.setSelected(true); + radio.add(_rbAll); + operationPanel.add(_rbAll); + + _rbGet = new JRadioButton(SNMPCommunityPanel._i18nOperationsGET); + _rbGet.setActionCommand(_cmdGet); + _rbGet.addActionListener(radioListener); + radio.add(_rbGet); + operationPanel.add(_rbGet); + + _rbSet = new JRadioButton(SNMPCommunityPanel._i18nOperationsSET); + _rbSet.setActionCommand(_cmdSet); + _rbSet.addActionListener(radioListener); + radio.add(_rbSet); + operationPanel.add(_rbSet); + + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 1, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + add(operationPanel, gbc); + + } + + private ActionListener radioListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + _operation = e.getActionCommand(); + } + }; + + public String getCommunity() { + return _community = _txtCommunity.getText().trim(); + } + + public void setCommunity(String community) { + _txtCommunity.setText(_community = community); + } + + public String getOperation() { + return _operation; + } + + public void setOperation(String operation) { + _operation = operation; + if (operation.equals(_cmdAll)) { + _rbAll.setSelected(true); + } else if (operation.equals(_cmdGet)) { + _rbGet.setSelected(true); + } else if (operation.equals(_cmdSet)) { + _rbSet.setSelected(true); + } else { + Thread.currentThread().dumpStack(); + Debug.println("ERROR: Bad operation selector <" + + operation + ">"); + _rbAll.setSelected(true); + _operation = _cmdAll; + } + } + + public JTextField[] getTextComponents() { + return new JTextField[]{ _txtCommunity }; + } +} diff --git a/src/com/netscape/management/admserv/panel/SNMPConfigPanel.java b/src/com/netscape/management/admserv/panel/SNMPConfigPanel.java new file mode 100644 index 0000000..5176e31 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/SNMPConfigPanel.java @@ -0,0 +1,97 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.awt.*; +import javax.swing.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 11/28/97 + * @author miodrag@netscape.com + */ +public class SNMPConfigPanel extends TabbedConfigPanel { + static ResourceSet _resource; + static String _i18nStatusTab, _i18nCommunitiesTab, _i18nManagersTab; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nStatusTab = _resource.getString("status","Status"); + _i18nCommunitiesTab = _resource.getString("snmp","CommunitiesTab"); + _i18nManagersTab = _resource.getString("snmp","ManagersTab"); + } + + IConfigDataModel _configData; + ConsoleInfo _consoleInfo; + String _taskURL; + String _username; + String _password; + + SNMPStatusPanel _statusTab; + SNMPCommunityPanel _communityTab; + SNMPManagerPanel _managerTab; + + + public SNMPConfigPanel(ConsoleInfo consoleInfo) { + + _consoleInfo = consoleInfo; + _configData = new CGISNMPSetup(consoleInfo); + + addTabPanes(); + } + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) + throws ConfigPanelException { + super.setDataModel(_configData = data); + } + + protected void addTabPanes() { + addTab(_i18nStatusTab, null, + _statusTab = new SNMPStatusPanel("", _consoleInfo)); + + + addTab(_i18nCommunitiesTab, null, + _communityTab = new SNMPCommunityPanel("", _configData)); + + addTab(_i18nManagersTab, null, + _managerTab = new SNMPManagerPanel("", _configData)); + } + + public void initialize() throws ConfigPanelException { + + try { + if (! _configData.isLoaded()) { + _configData.load(); + } + super.initialize(); // initialize all + } catch (ConfigPanelException e) { + throw e; + } + } +} + diff --git a/src/com/netscape/management/admserv/panel/SNMPManagerPanel.java b/src/com/netscape/management/admserv/panel/SNMPManagerPanel.java new file mode 100644 index 0000000..14f5061 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/SNMPManagerPanel.java @@ -0,0 +1,517 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.nmclf.SuiConstants; + +/** + * + * @version 0.1 11/23/97 + * @author miodrag@netscape.com + */ +public class SNMPManagerPanel extends PluginConfigPanel { + + IConfigDataModel _configData; + + static ResourceSet _resource; + static String _i18nDescription, _i18nEditDialogTitle, + _i18nAddDialogTitle; + static String _i18nManager, _i18nPort, _i18nCommunity, + _i18nDetailsGroupbox; + static String _i18nMsgEnterManager, _i18nMsgEntryExists, + _i18nMsgCanNotRename; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nDescription = _resource.getString("snmpmgr","Description"); + _i18nEditDialogTitle = _resource.getString("snmpmgr","EditDialogTitle"); + _i18nAddDialogTitle = _resource.getString("snmpmgr","AddDialogTitle"); + _i18nManager = _resource.getString("snmpmgr","Manager"); + _i18nPort = _resource.getString("snmpmgr","Port"); + _i18nCommunity = _resource.getString("snmpmgr","Community"); + _i18nDetailsGroupbox = _resource.getString("snmpmgr","DetailsGroupbox"); + _i18nMsgEnterManager = _resource.getString("snmpmgr","MsgEnterManager"); + _i18nMsgEntryExists = _resource.getString("snmpmgr","MsgEntryExists"); + _i18nMsgCanNotRename = _resource.getString("snmpmgr","MsgCanNotRename"); + } + + Help _help; + + // Panel Controls + JLabel _lblDescription; + ManagerList _managerList; + Vector _managers = new Vector(); + + public SNMPManagerPanel(String title, IConfigDataModel data) { + super(title); + _configData = data; + + setLayout(new BorderLayout()); + add(makePanel(), BorderLayout.NORTH); + _help = new Help(_resource); + } + + public void showHelp() { + _help.contextHelp("SNMPManagerHelp"); + } + + + public void initialize() throws ConfigPanelException { + setPanelContent(_configData); + } + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) + throws ValidationException { + _configData = data; + if (_configData.isLoaded()) { + setPanelContent(_configData); + } + } + + public void resetContent() throws ConfigPanelException { + setPanelContent(_configData); + } + + public void applyChanges() throws ValidationException { + getPanelContent(_configData); + } + + public void registerEditComponents(EditMonitor editMonitor) { + _managerList.addListDataListener(editMonitor); + } + + public void setPanelContent(IConfigDataModel data) + throws ValidationException { + String value = data.getAttribute(AttrNames.SNMP_MANAGERS); + _managers = CGISNMPSetup.stringToManagerVector(value); + _managerList.setManagers(_managers); + } + + public void getPanelContent(IConfigDataModel data) + throws ValidationException { + String value = CGISNMPSetup.managerVectorToString(_managers); + Debug.println("managers value = <" + value + ">"); + data.setAttribute(AttrNames.SNMP_MANAGERS, value); + } + + /** + * + */ + protected JComponent makePanel() { + JPanel p = new JPanel(); + GBC gbc = new GBC(); + GridBagLayout gbl; + JPanel ctrlGroup; + + p.setLayout(gbl = new GridBagLayout()); + + JLabel lbl = new JLabel(_i18nDescription); + gbc.setInsets(10, 0, 10, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(lbl, gbc); + + _managerList = new ManagerList(_managers); + //gbc.setInsets(topInset,leftColInset,0,0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(_managerList, gbc); + + return p; + } +} + +/** + * A custom component that enables element in the list to be edited: + * add, edit, remove + */ +class ManagerList extends EditableList { + + ManagerEditPanel _editPanel; + JPanel _detailsPanel; + JLabel _lblDetailsManager, _lblDetailsPort, _lblDetailsCommunity; + Vector _managers; + int _editEntryIdx = -1; + + static String _i18nEditMgr, _i18nAddMgr, _i18nRemoveMgr; + + static { + _i18nEditMgr = _resource.getString("snmpmgr","EditMgrToolTip"); + _i18nAddMgr = _resource.getString("snmpmgr","AddMgrToolTip"); + _i18nRemoveMgr = _resource.getString("snmpmgr","RemoveMgrToolTip"); + } + + public ManagerList(Vector managers) { + setManagers(managers); + } + + public void setManagers(Vector managers) { + _managers = managers; + setList(getManagerNames(_managers)); + } + + Vector getManagerNames(Vector entryList) { + Vector v = new Vector(entryList.size()); + for (int i = 0; i < entryList.size(); i++) { + Hashtable entry = (Hashtable) entryList.elementAt(i); + v.addElement(entry.get(CGISNMPSetup.MANAGER_NAME)); + } + return v; + } + + public JPanel getEditPanel() { + _editPanel = new ManagerEditPanel(); + JTextField[] txtComponents = _editPanel.getTextComponents(); + setEditPanelInitalFocusComponent(txtComponents[0]); + setEditPanelCommitOnEnterComponents(txtComponents); + return _editPanel; + } + + public String getEditTitle() { + return SNMPManagerPanel._i18nEditDialogTitle; + } + + public String getAddTitle() { + return SNMPManagerPanel._i18nAddDialogTitle; + } + + public String getEditToolTip() { + return _i18nEditMgr; + } + + public String getAddToolTip() { + return _i18nAddMgr; + } + + public String getRemoveToolTip() { + return _i18nRemoveMgr; + } + + public ResourceSet getHelpResourceSet() { + return SNMPManagerPanel._resource; + }; + public String getHelpToken() { + return "editSNMPManagerHelp"; + } + + public void validateEdit() throws ValidationException { + String manager = _editPanel.getManager(); + if (manager.length() == 0) { + throw new ValidationException( SNMPManagerPanel._i18nManager, + SNMPManagerPanel._i18nMsgEnterManager); + } + int idx = findManager(manager); + if (idx >= 0) { + if (_editEntryIdx == -1) { // create new entry in progress + throw new ValidationException( + SNMPManagerPanel._i18nManager, + SNMPManagerPanel._i18nMsgEntryExists); + } else if (idx != _editEntryIdx) { + throw new ValidationException( + SNMPManagerPanel._i18nManager, + SNMPManagerPanel._i18nMsgCanNotRename); + } + } + } + + public JPanel getDetailsPanel() { + return _detailsPanel = createDetailsPanel(); + } + + public String getDetailsTitle() { + return SNMPManagerPanel._i18nDetailsGroupbox; + } + + private JPanel createDetailsPanel() { + JPanel p = new JPanel(new GridBagLayout()); + GBC gbc = new GBC(); + + JLabel lbl = new JLabel(SNMPManagerPanel._i18nManager); + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor + GBC.BOTH); //fill + p.add(lbl, gbc); + + _lblDetailsManager = new JLabel(" "); + gbc.setInsets(0, 10, 0, 0); + gbc.setGrid(1, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_lblDetailsManager, gbc); + + lbl = new JLabel(SNMPManagerPanel._i18nPort); + gbc.setInsets(10, 0, 0, 0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + p.add(lbl, gbc); + + _lblDetailsPort = new JLabel(" "); + gbc.setInsets(10, 10, 0, 0); + gbc.setGrid(1, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_lblDetailsPort, gbc); + + lbl = new JLabel(SNMPManagerPanel._i18nCommunity); + gbc.setInsets(10, 0, 0, 0); + gbc.setGrid(0, 2, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + p.add(lbl, gbc); + + _lblDetailsCommunity = new JLabel(" "); + gbc.setInsets(10, 10, 0, 0); + gbc.setGrid(1, 2, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_lblDetailsCommunity, gbc); + + return p; + + } + + public void setEditPanelParameters(String item) { + if (item == null) { //add + _editPanel.setCommunity("public"); + _editPanel.setPort("162"); + _editPanel.setManager(""); + _editEntryIdx = -1; + } else { //edit + int idx = findManager(item); + if (idx >= 0) { + _editEntryIdx = idx; + + Hashtable entry = (Hashtable)_managers.elementAt(idx); + String manager = + (String) entry.get(CGISNMPSetup.MANAGER_NAME); + String port = (String) entry.get(CGISNMPSetup.MANAGER_PORT); + String community = (String) entry.get( + CGISNMPSetup.MANAGER_COMMUNITY); + + _editPanel.setManager(manager); + _editPanel.setPort(port); + _editPanel.setCommunity(community); + } else { + Debug.println("ERROR: Manager not found: " + item); + } + } + } + + public String getEditPanelItem() { + return _editPanel.getManager(); + } + + + private int findManager(String name) { + return CGISNMPSetup.findEntry(_managers, + CGISNMPSetup.MANAGER_NAME , name); + } + + public void createItem(String item) { + _managers.addElement( + CGISNMPSetup.createManagerEntry(new String(item), + new String(_editPanel.getPort()), + new String(_editPanel.getCommunity()))); + //dumpData(); + } + + public void removeItem(String item) { + int idx = findManager(item); + if (idx >= 0) { + _managers.removeElementAt(idx); + } else { + Debug.println("ERROR: Manager not found: " + item); + } + //dumpData(); + } + + public void updateItem(String item, boolean isRenamed) { + int idx = findManager(item); + if (idx >= 0) { + Hashtable entry = CGISNMPSetup.createManagerEntry( + new String(_editPanel.getManager()), + new String(_editPanel.getPort()), + new String(_editPanel.getCommunity())); + + _managers.setElementAt(entry, idx); + } else { + Debug.println("ERROR: Manager not found: " + item); + } + //dumpData(); + } + + + private void dumpData() { + if (_managers.size() == 0) { + Debug.println("No entries"); + return; + } + + for (int i = 0; i < _managers.size(); i++) { + Hashtable entry = (Hashtable)_managers.elementAt(i); + String manager = (String) entry.get(CGISNMPSetup.MANAGER_NAME); + String port = (String) entry.get(CGISNMPSetup.MANAGER_PORT); + String community = + (String) entry.get(CGISNMPSetup.MANAGER_COMMUNITY); + Debug.print(i + "=[" + manager + " " + port + " " + + community + "] "); + } + Debug.println(""); + } + + public void selectItem(String item) { + + //Debug.println("selectItem " + item); + + if (item == null) { + _lblDetailsManager.setText(""); + _lblDetailsPort.setText(""); + _lblDetailsCommunity.setText(""); + return; + } + + int idx = findManager(item); + + if (idx >= 0) { + Hashtable entry = (Hashtable)_managers.elementAt(idx); + String manager = (String) entry.get(CGISNMPSetup.MANAGER_NAME); + String port = (String) entry.get(CGISNMPSetup.MANAGER_PORT); + String community = + (String) entry.get(CGISNMPSetup.MANAGER_COMMUNITY); + + _lblDetailsManager.setText(manager); + _lblDetailsPort.setText(port); + _lblDetailsCommunity.setText(community); + } else { + Debug.println("ERROR: Manager not found: " + item); + } + } + +} + +/** + * Manager Edit Dialog + */ +class ManagerEditPanel extends JPanel implements SuiConstants { + String _manager = "", _port = "", _community = ""; + JTextField _txtManager, _txtPort, _txtCommunity; + + public ManagerEditPanel() { + createLayout(); + } + + private void createLayout() { + GBC gbc = new GBC(); + setLayout(new GridBagLayout()); + + JLabel lblManager = new JLabel(SNMPManagerPanel._i18nManager); + lblManager.setFont(BaseConfigPanel.getLabelFont()); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 0, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + add(lblManager, gbc); + + _txtManager = new JTextField(_manager, 16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 0, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, //anchor + GBC.HORIZONTAL); //fill + add(_txtManager, gbc); + lblManager.setLabelFor(_txtManager); + + JLabel lblPort = new JLabel(SNMPManagerPanel._i18nPort); + lblPort.setFont(BaseConfigPanel.getLabelFont()); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + add(lblPort, gbc); + + _txtPort = new JTextField(_port, 6); + _txtPort.setDocument(FilteredInputDocument.allowDigitsOnly()); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, //anchor + GBC.NONE); //fill + add(_txtPort, gbc); + lblPort.setLabelFor(_txtPort); + + JLabel lblCommunity = new JLabel(SNMPManagerPanel._i18nCommunity); + lblCommunity.setFont(BaseConfigPanel.getLabelFont()); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, 2, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + add(lblCommunity, gbc); + + _txtCommunity = new JTextField(_community, 16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, 2, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHWEST, //anchor + GBC.HORIZONTAL); //fill + add(_txtCommunity, gbc); + lblCommunity.setLabelFor(_txtCommunity); + } + + public String getManager() { + return _manager = _txtManager.getText().trim(); + } + + public void setManager(String manager) { + _txtManager.setText(_manager = manager); + } + + public String getCommunity() { + return _community = _txtCommunity.getText().trim(); + } + + public void setCommunity(String community) { + _txtCommunity.setText(_community = community); + } + + public String getPort() { + return _port = _txtPort.getText().trim(); + } + + public void setPort(String port) { + _txtPort.setText(_port = port); + } + + public JTextField[] getTextComponents() { + return new JTextField[]{ _txtManager, _txtPort, _txtCommunity }; + } +} diff --git a/src/com/netscape/management/admserv/panel/SNMPStatusPanel.java b/src/com/netscape/management/admserv/panel/SNMPStatusPanel.java new file mode 100644 index 0000000..bbb605a --- /dev/null +++ b/src/com/netscape/management/admserv/panel/SNMPStatusPanel.java @@ -0,0 +1,322 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.util.*; +import java.awt.*; +import java.net.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.border.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; + +/** + * + * @version 0.1 02/10/98 + * @author miodrag@netscape.com + */ +public class SNMPStatusPanel extends PluginConfigPanel { + + ConsoleInfo _target, _consoleInfo; + Hashtable _statusTable = new Hashtable(); + + static ResourceSet _resource; + static String _i18nAgentOn, _i18nAgentOff, _i18nAgentUnknown; + static String _i18nOn, _i18nOff, _i18nUnknown, _i18nMasterAgent, + _i18nStatus; + static String _i18nCheckStatusButton, _i18nRestartButton, + _i18nStopButton; + static String _i18nDialogTitleStop, _i18nDialogTitleRestart, + _i18nDialogTitleStatus; + static String _i18nCheckStatusToolTip, _i18nRestartToolTip, _i18nStopToolTip; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nAgentOn = _resource.getString("status","AgentOn"); + _i18nAgentOff = _resource.getString("status","AgentOff"); + _i18nAgentUnknown = _resource.getString("status","AgentUnknown"); + _i18nOn = _resource.getString("status","On"); + _i18nOff = _resource.getString("status","Off"); + _i18nUnknown = _resource.getString("status","Unknown"); + _i18nMasterAgent = _resource.getString("status","MasterAgent"); + _i18nStatus = _resource.getString("status","Status"); + _i18nCheckStatusButton = _resource.getString("status","CheckStatus"); + _i18nRestartButton = _resource.getString("status","Restart"); + _i18nStopButton = _resource.getString("status","Stop"); + _i18nDialogTitleStop = _resource.getString("status","DialogStopAgent"); + _i18nDialogTitleRestart = _resource.getString("status","DialogRestartAgent"); + _i18nDialogTitleStatus = _resource.getString("status","DialogStatusAgent"); + _i18nCheckStatusToolTip = _resource.getString("status","CheckStatusToolTip"); + _i18nRestartToolTip = _resource.getString("status","RestartToolTip"); + _i18nStopToolTip = _resource.getString("status","StopToolTip"); + } + + static Help _help; + + static String _cmdStatus = "status", _cmdRestart = "restart", + _cmdStop = "stop"; + + // Panel Controls + JLabel _lblStatus; + ButtonBar _buttons; + String _agentColumn; + + public SNMPStatusPanel(String title, ConsoleInfo consoleInfo) { + super(title); + _target = _consoleInfo = consoleInfo; + + setLayout(new BorderLayout()); + add(makePanel(), BorderLayout.NORTH); + _help = new Help(_resource); + + updateStatus(); + + } + + public void showHelp() { + _help.contextHelp("SNMPStatusHelp"); + } + + + void updateStatus() { + _lblStatus.setVisible(true); + validate(); + String agent = (String)_target.get("SERVER_NAME"); + String status = (String)_statusTable.get(agent); + status = (status == null) ? _i18nUnknown : status; + if (status.equals(_i18nOn)) { + _lblStatus.setText(_i18nAgentOn); + } else if (status.equals(_i18nOff)) { + _lblStatus.setText(_i18nAgentOff); + } else { + _lblStatus.setText(_i18nAgentUnknown); + } + } + + void updateStatus(String agent) { + String status = (String)_statusTable.get(agent); + status = (status == null) ? _i18nUnknown : status; + + if (status.equals(_i18nOn)) { + _lblStatus.setText(_i18nAgentOn); + } else if (status.equals(_i18nOff)) { + _lblStatus.setText(_i18nAgentOff); + } else { + _lblStatus.setText(_i18nAgentUnknown); + } + + } + + public void initialize() throws ConfigPanelException { + checkStatus(_consoleInfo, true); + } + + public IConfigDataModel getDataModel() { + return null; + } + + public void setDataModel(IConfigDataModel data) + throws ValidationException { + if (data != null) { + if (data instanceof CGISNMPSetup) { + _target = ((CGISNMPSetup) data).getConsoleInfo(); + } else { + _target = _consoleInfo; + } + updateStatus(); + } + } + + public void resetContent() throws ConfigPanelException { + } + + public void applyChanges() throws ValidationException { + } + + public void registerEditComponents(EditMonitor editMonitor) { + } + + /** + * + */ + protected JComponent makePanel() { + JPanel p = new JPanel(); + GBC gbc = new GBC(); + GridBagLayout gbl; + JPanel ctrlGroup; + //int row=0; + + p.setLayout(gbl = new GridBagLayout()); + + _lblStatus = new JLabel(_i18nAgentUnknown); + gbc.setInsets(10, 0, 10, 0); + gbc.setGrid(0, 0, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(_lblStatus, gbc); + + gbc.setInsets(10, 0, 10, 0); + gbc.setGrid(0, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(new JLabel(), gbc); // spacer + + // buttons + _buttons = new ButtonBar(new String[]{_cmdStatus, _cmdRestart, + _cmdStop}, + new String[]{_i18nCheckStatusButton, + _i18nRestartButton, _i18nStopButton}, + new String[]{_i18nCheckStatusToolTip, + _i18nRestartToolTip, _i18nStopToolTip}, + false); + _buttons.addActionListener(_btnListener); + _buttons.setBorder(new EmptyBorder(0, 10, 0, 0)); + + gbc.setInsets(10, 0, 10, 0); + gbc.setGrid(1, 1, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.NORTHEAST, //anchor + GBC.HORIZONTAL); //fill + + p.add(_buttons, gbc); + + return p; + } + + + class StatusCheckListener implements IAdminOperationListener { + AdminOperation _op; + + public StatusCheckListener(AdminOperation op) { + _op = op; + } + + public void cgiRequestCompleted(ConsoleInfo ci) { + String tabStatus = _i18nUnknown; + if (_op.getResultStatus() == 0) { + Hashtable res = _op.getResultData(); + //Debug.printHashtable("snmp status res", res); + String statusAttr = (String) res.get("status"); + if (statusAttr == null) { + Debug.println("status attr missing"); + } else if (statusAttr.equalsIgnoreCase("ON")) { + tabStatus = _i18nOn; + } else { + tabStatus = _i18nOff; + } + } + + String agent = (String) ci.get("SERVER_NAME"); + _statusTable.put(agent, tabStatus); + updateStatus(agent); + } + } + + class StopStartListener implements IAdminOperationListener { + AdminOperation _op; + boolean _stop; + + public StopStartListener(AdminOperation op, boolean stop) { + _op = op; + _stop = stop; + } + + public void cgiRequestCompleted(ConsoleInfo ci) { + String tabStatus = _i18nUnknown; + if (_op.getResultStatus() == 0) { + tabStatus = _stop ? _i18nOff : _i18nOn; + + } + String agent = (String) ci.get("SERVER_NAME"); + _statusTable.put(agent, tabStatus); + updateStatus(agent); + } + } + + protected void checkStatus(ConsoleInfo ci, boolean init) { + String taskURL = "admin-serv/tasks/Operation/SNMPControl?ACTION=STATUS"; + AdminOperation operation = + new AdminOperation(ci, taskURL); + StatusCheckListener listener = new StatusCheckListener(operation); + operation.monitorOperation(_i18nDialogTitleStatus + " ...", + listener); + + if (init || operation.getDialog() != null || + operation.getFrame() != null) + return; + + String title = _i18nDialogTitleStatus; + DialogFrame dialog = + new DialogFrame(this, title, operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + } + + protected void restart(ConsoleInfo ci) { + String taskURL = "admin-serv/tasks/Operation/SNMPControl?ACTION=RESTART"; + AdminOperation operation = + new AdminOperation(ci, taskURL); + StopStartListener listener = + new StopStartListener(operation, false); + operation.monitorOperation("", listener); + String title = _i18nDialogTitleRestart; + DialogFrame dialog = + new DialogFrame(this, title, operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + } + + protected void stop(ConsoleInfo ci) { + String taskURL = "admin-serv/tasks/Operation/SNMPControl?ACTION=STOP"; + AdminOperation operation = + new AdminOperation(ci, taskURL); + StopStartListener listener = new StopStartListener(operation, true); + operation.monitorOperation("", listener); + String title = _i18nDialogTitleStop; + DialogFrame dialog = + new DialogFrame(this, title, operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + } + + ActionListener _btnListener = new ActionListener() { + + public void actionPerformed(ActionEvent e) { + String cmd = e.getActionCommand(); + if (cmd.equals(_cmdStatus)) { + checkStatus(_target, false); + } else if (cmd.equals(_cmdRestart)) { + restart(_target); + } else if (cmd.equals(_cmdStop)) { + stop(_target); + } else { + Debug.println( + "SNMPStatusPanel: Unknown acction command " + + cmd); + } + } + }; +} + diff --git a/src/com/netscape/management/admserv/panel/StopOperation.java b/src/com/netscape/management/admserv/panel/StopOperation.java new file mode 100644 index 0000000..1c82fc6 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/StopOperation.java @@ -0,0 +1,94 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.net.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.comm.CommRecord; +import com.netscape.management.client.comm.CommManager; +import java.io.ByteArrayInputStream; + +public class StopOperation extends AdminOperation { + String _i18nSendRequest = _resource.getString("stop","SendRequest"); + String _i18nAccepted = _resource.getString("stop","Accepted"); + String _i18nWait = _resource.getString("stop","Wait"); + String _i18nDone = _resource.getString("stop","Done"); + + boolean _serverRunning = true; + + public StopOperation(ConsoleInfo consoleInfo) { + super(consoleInfo, "admin-serv/tasks/Operation/Stop"); + createActionPanel(/*multiLined=*/true); + } + + + /** + * Issue stop request and record pid returned in the response. Afterwards, poll + * for pid until new pid is detected + */ + public void performOperationalTask(ConsoleInfo ci, + String taskURL) throws RemoteRequestException { + AdmTask task = null; + _serverRunning = true; + _actionPanel.setStatusText(_i18nSendRequest); + super.performOperationalTask(ci, taskURL); + _actionPanel.setStatusText(_i18nAccepted); + + long t0 = System.currentTimeMillis(); + + _actionPanel.setStatusText(_i18nWait); + _actionPanel.setStatusTextSameLIne("\n"); + + // Poll for loss of connection to the server + while (_serverRunning) { + + // Sleep 3 sec between consecutive poll requests + try { + Thread.currentThread().sleep(3000); + } catch (Exception e) {} + + _serverRunning = AdminConfigData.isRunning(ci.getAdminURL()); + _actionPanel.setStatusTextSameLIne("*"); + + // Start a new line if after 90 sec restart not detected + if ((System.currentTimeMillis() - t0) > 90000) { + t0 = System.currentTimeMillis(); + _actionPanel.setStatusTextSameLIne("\n"); + } + } + _actionPanel.setStatusText(_i18nDone + "\n"); + + // Indicate that restart can not be done from the console any more + IRestartControl restartControl = + (IRestartControl) ci.get(IRestartControl.ID); + if (restartControl != null) { + restartControl.setServerShutdown(true); + } else { + Debug.println("StopOperation: restart activator not in ConsoleInfo"); + } + + Debug.println("StopOperation time = " + + (System.currentTimeMillis() - t0) / 1000.); + } +} + diff --git a/src/com/netscape/management/admserv/panel/TurnOnSSL.java b/src/com/netscape/management/admserv/panel/TurnOnSSL.java new file mode 100644 index 0000000..32a0c03 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/TurnOnSSL.java @@ -0,0 +1,495 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.client.util.ModalDialogUtil; +import com.netscape.management.client.security.*; +import netscape.ldap.*; + +import javax.swing.*; +import javax.swing.border.*; +import java.awt.*; +import java.awt.event.*; +import java.util.*; +import java.util.StringTokenizer; +import java.net.URL; +import java.lang.String; + +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.util.*; +import com.netscape.management.nmclf.*; + +public class TurnOnSSL implements IPluginConfigPanel, EncryptionOptions, IClientAuthOptions{ + + static ResourceSet _resource; + EditMonitor _monitor = null; + ConsoleInfo _consoleInfo; + JPanel encryptionPanel = null; + Hashtable securitySettings = new Hashtable(); + EncryptionPanel _adminEncryptionPanel; + boolean _isDirty = false; + boolean _domestic = false; + ClientAuthPanel _clientAuthPanel; + + static String _i18nMsgNoSslPreferences, _i18nMsgNoSslFamily, _i18nMsgNoCertificate, _i18nMsgSaved; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nMsgNoSslPreferences = _resource.getString("TurnOnSSL","MsgNoSslPreferences"); + _i18nMsgNoSslFamily = _resource.getString("TurnOnSSL","MsgNoSslFamily"); + _i18nMsgNoCertificate = _resource.getString("TurnOnSSL","MsgNoCertificate"); + _i18nMsgSaved = _resource.getString("TurnOnSSL","Saved"); + } + + public void clientAuthSettingChanged(int type) { + Debug.println("TurnOnSSL:clientAuthSettingChanged:"+type); + securitySettings.put("clientauth", (type==CLIENT_AUTH_REQUIRED)?"on":"off"); + setDirty(true); + } + public int getClientAuthSetting() { + return securitySettings.get("clientauth").equals("on")?CLIENT_AUTH_REQUIRED:CLIENT_AUTH_DISABLED; + } + + public int[] getClientAuthUIOption() { + int[] uiOptions = { CLIENT_AUTH_DISABLED, CLIENT_AUTH_REQUIRED }; + return uiOptions; + } + + + private void setDirty(boolean dirty) { + if (_monitor != null) { + _monitor.setDirtyFlag(dirty); + _isDirty = dirty; + } + } + + + void changeSecuritySetting(String key, String val) { + try { + securitySettings.put(key, val); + setDirty(true); + //Debug.printHashtable("Security Setting", securitySettings); + + /*System.out.println("TEST="+key+":"+val);*/ + if (key.equals("security")) { + _clientAuthPanel.setEnabled(val.equals("on")); + } + } catch (Exception e) { + Debug.println("TurnOnSSL: unable to change security setting"); + } + } + + public void securityEnabledChanged(boolean enabled){ + changeSecuritySetting("security", enabled?"on":"off"); + Debug.println("Security enabled:"+(enabled?"on":"off")); + //Debug.println(securitySettings); + } + + + public void cipherFamilyEnabledChanged(String cipherFamily, boolean enabled){ + Object familyList = securitySettings.get("familyList"); + if ((familyList == null) || (familyList.toString().indexOf(cipherFamily) == -1)) { + String listString = familyList.toString(); + securitySettings.put("familyList", listString.length()>0?(listString+","+cipherFamily):cipherFamily); + } + + changeSecuritySetting(cipherFamily+"-activated", enabled?"on":"off"); + Debug.println("Enable cipherFamily:"+cipherFamily+":"+enabled); + //System.out.println(securitySettings); + } + + public void selectedDeviceChanged(String cipherFamily, String device){ + changeSecuritySetting(cipherFamily+"-token", device); + + Debug.println("Selected device:"+cipherFamily+":"+device); + //System.out.println(securitySettings); + } + + public void selectedCertificateChanged(String cipherFamily, String certName){ + changeSecuritySetting(cipherFamily+"-cert", certName); + Debug.println("Selected cert"+cipherFamily+":"+certName); + //System.out.println(securitySettings); + } + + public void showCipherPreferenceDialog(String cipherFamily){ + Debug.println("Show cipher preference dialog:"+cipherFamily); + CipherPreferenceDialog cipherPref = null; + + if (cipherFamily.toLowerCase().equals("fortezza")) { + cipherPref = new CipherPreferenceDialog(null, + "", + (String)(securitySettings.get("ssl3")), + "") { + public void cipherStateChanged(String SSLVersion, String cipher, boolean enabled) { + setDirty(true); + } + }; + } else { + cipherPref = new CipherPreferenceDialog(null, + (String)(securitySettings.get("ssl2")), + (String)(securitySettings.get("ssl3")), + (String)(securitySettings.get("tls"))) { + public void cipherStateChanged(String SSLVersion, String cipher, boolean enabled) { + setDirty(true); + } + }; + } + + cipherPref.setVisible(true); + + if (!(cipherPref.isCancel())) { + securitySettings.put("ssl2", cipherPref.getCipherPreference(cipherPref.SSL_V2)); + securitySettings.put("ssl3", cipherPref.getCipherPreference(cipherPref.SSL_V3)); + securitySettings.put("tls", cipherPref.getCipherPreference(cipherPref.SSL_TLS)); + + securitySettings.put("ssl2-activated", cipherPref.isSSLVersionEnabled(cipherPref.SSL_V2)?"on":"off"); + securitySettings.put("ssl3-activated", cipherPref.isSSLVersionEnabled(cipherPref.SSL_V3)?"on":"off"); + securitySettings.put("tls-activated", cipherPref.isSSLVersionEnabled(cipherPref.SSL_TLS)?"on":"off"); + } + } + + public void setSecurityIsDomestic(boolean domestic) { + _domestic = domestic; + + Object ssl2Setting = securitySettings.get("ssl2"); + Object ssl3Setting = securitySettings.get("ssl2"); + Object tlsSetting = securitySettings.get("tls"); + + //construct a default cipher preference dialog, and get the default settings + CipherPreferenceDialog cipherPref = new CipherPreferenceDialog(null, true, true, true, domestic, false); + + if ((ssl2Setting == null) || + (ssl2Setting.toString().length() == 0) || + (ssl2Setting.toString().equals("blank"))) { + securitySettings.put("ssl2", cipherPref.getCipherPreference(cipherPref.SSL_V2)); + } + if ((ssl3Setting == null) || + (ssl3Setting.toString().length() == 0) || + (ssl3Setting.toString().equals("blank"))) { + securitySettings.put("ssl3", cipherPref.getCipherPreference(cipherPref.SSL_V3)); + } + if ((tlsSetting == null) || + (tlsSetting.toString().length() == 0) || + (tlsSetting.toString().equals("blank"))) { + securitySettings.put("tls", cipherPref.getCipherPreference(cipherPref.SSL_TLS)); + } + + Object ssl2On = securitySettings.get("ssl2-activated"); + Object ssl3On = securitySettings.get("ssl3-activated"); + Object tlsOn = securitySettings.get("tls-activated"); + if ((ssl2On == null) || + (ssl2On.toString().equals("blank")) || + (ssl2On.toString().length() == 0) ) { + securitySettings.put("ssl2-activated", "on"); + } + if ((ssl3On == null) || + (ssl3On.toString().equals("blank")) || + (ssl3On.toString().length() == 0)) { + securitySettings.put("ssl3-activated", "on"); + } + if ((tlsOn == null) || + (tlsOn.toString().equals("blank")) || + (tlsOn.toString().length() == 0) ) { + securitySettings.put("tls-activated", "on"); + } + } + + public boolean isSecurityEnabled() { + boolean securityEnabled = false; + try { + securityEnabled = securitySettings.get("security").equals("on"); + } catch (Exception e) { + Debug.println("TurnOnSSL: no security setting"); + } + return securityEnabled; + } + + public boolean isCipherFamilyEnabled(String cipherFamily) { + boolean cipherFamilyEnabled = false; + try { + cipherFamilyEnabled = securitySettings.get(cipherFamily+"-activated").equals("on"); + } catch (Exception e) { + Debug.println("TurnOnSSL: no security setting"); + } + Debug.println("Cipher family enabled:"+(cipherFamilyEnabled?"true":"false")); + return cipherFamilyEnabled; + } + + public String getSelectedCertificate(String cipherFamily) { + String certName = ""; + try { + certName = (String)(securitySettings.get(cipherFamily+"-cert")); + } catch (Exception e) { + Debug.println("TurnOnSSL: no security setting"); + } + Debug.println("Get selected cert:"+certName); + return certName; + } + + public String getSelectedDevice(String cipherFamily) { + String deviceName = ""; + try { + deviceName = (String)(securitySettings.get(cipherFamily+"-token")); + } catch (Exception e) { + Debug.println("TurnOnSSL: no security setting"); + } + Debug.println("Get selected device:"+deviceName); + return deviceName; + } + + + + public TurnOnSSL(ConsoleInfo consoleInfo) { + + _consoleInfo = consoleInfo; + Debug.println("TurnOnSSL:TurnOnSSL()"); + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + + try { + AdmTask task = new AdmTask( + new URL(_consoleInfo.getAdminURL() + "admin-serv/tasks/configuration/SSLActivate"), + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + task.exec(); + //System.out.println(task.getStatus()); + //if (task.getStatus()) { do some error message here } + Debug.println(task.getResultString().toString()); + StringTokenizer st = new StringTokenizer( + task.getResultString().toString(), "\n", false); + while (st.hasMoreTokens()) { + String line = st.nextToken(); + + int index = line.indexOf("="); + if (index != -1) { + Object key = line.substring(0, index); + Object val = securitySettings.get(key); + String hashVal = line.substring(index + 1, line.length()); + if (val == null) { + securitySettings.put(key, + hashVal.toLowerCase().equals("null")?"":hashVal); + + //changeSecuritySetting(key, hashVal.toLowerCase().equals("null")?"":hashVal); + } else if (!(hashVal.toString().toLowerCase().equals("null"))) { + securitySettings.put(key, + val + ","+ + hashVal); + } + } + } + + } + catch (Exception e) { + //e.printStackTrace(); + Debug.println(e.toString()); + } + + if ((securitySettings.get("clientauth") == null) || securitySettings.get("clientauth").toString().equals("")) { + //initialize the default setting + securitySettings.put("clientauth", "off"); + } + + + //Debug.printHashtable("Security Setting", securitySettings); + + //addEncryptionPaneListener(this); + /*resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + noTokenSelected = resource.getString("TurnOnSSL", "noTokenSelected"); + noCertSelected = resource.getString("TurnOnSSL", "noCertSelected"); + noCipherSelected = resource.getString("TurnOnSSL", "noCipherSelected"); + + setupEncryption();*/ + } + + public String getTitleText() { + return ""; + } + + + public JPanel getPanel() { + Debug.println("TurnOnSSL:getPanel()"); + if (encryptionPanel == null) { + encryptionPanel = new JPanel(); + encryptionPanel.setLayout(new GridBagLayout()); + _adminEncryptionPanel = new EncryptionPanel(_consoleInfo, (String)(_consoleInfo.get("SIE")), this); + GridBagUtil.constrain(encryptionPanel, _adminEncryptionPanel, + 0, 0, 1, 1, + 1.0, 0.0, + GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + 0, 0, 0, 0); + + _clientAuthPanel = new ClientAuthPanel(this); + _clientAuthPanel.setBorder(new CompoundBorder(new EtchedBorder(), + new EmptyBorder(SuiConstants.COMPONENT_SPACE, SuiConstants.COMPONENT_SPACE, + SuiConstants.COMPONENT_SPACE, SuiConstants.COMPONENT_SPACE))); + GridBagUtil.constrain(encryptionPanel, _clientAuthPanel, + 0, 1, 1, 1, + 1.0, 0.0, + GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + SuiConstants.COMPONENT_SPACE, 0, 0, 0); + + GridBagUtil.constrain(encryptionPanel, Box.createVerticalGlue(), + 0, 1, 1, 1, + 1.0, 1.0, + GridBagConstraints.WEST, GridBagConstraints.VERTICAL, + 0, 0, 0, 0); + + Object clientAuthSetting = securitySettings.get("security"); + _clientAuthPanel.setEnabled(clientAuthSetting==null?false:clientAuthSetting.toString().equals("on")); + + setDirty(false); + } + + return encryptionPanel; + } + + public IConfigDataModel getDataModel() { + return null; + } + + public void setDataModel(IConfigDataModel datModel) + throws ConfigPanelException { + } + public void initialize() throws ConfigPanelException { + } + + public void registerEditComponents(EditMonitor monitor) { + _monitor = monitor; + } + + public void resetContent() throws ConfigPanelException { + _adminEncryptionPanel.reset(); + _clientAuthPanel.reset(); + + Object clientAuthSetting = securitySettings.get("security"); + _clientAuthPanel.setEnabled(clientAuthSetting==null?false:clientAuthSetting.toString().equals("on")); + } + + public void applyChanges() throws ValidationException { + if (_isDirty) { + try { + + if (validEntries()) { + String adminURL = _consoleInfo.getAdminURL() + "admin-serv/tasks/configuration/SSLActivate"; + AdmTask task = new AdmTask(new URL(adminURL), + _consoleInfo.getAuthenticationDN(), + _consoleInfo.getAuthenticationPassword()); + + securitySettings.put("trustdb", (String)(_consoleInfo.get("SIE"))); + Debug.printHashtable("Security Setting", securitySettings); + task.setArguments(securitySettings); + task.exec(); + Debug.println(task.getResultString().toString()); + StringTokenizer st = new StringTokenizer(task.getResultString().toString(), "\n", false); + //AdminOperation.processAdmTaskStatus(adminURL, task, _consoleInfo); + if (task.getResult().get("NMC_Description") != null) { + _adminEncryptionPanel.setSaved(); + _clientAuthPanel.setSaved(); + SuiOptionPane.showMessageDialog(UtilConsoleGlobals.getActivatedFrame(), + _i18nMsgSaved); + } else if (task.getResult().get("NMC_ErrType") != null) { + SuiOptionPane.showMessageDialog(UtilConsoleGlobals.getActivatedFrame(), + task.getResult().get("NMC_ErrType") + "\n\n"+ + task.getResult().get("NMC_ErrInfo") + + ((task.getResult().get("NMC_ErrDetail") != + null) ? + "\n"+task.getResult().get("NMC_ErrDetail") : + "")); + } + + setDirty(false); + } + + } catch (ValidationException ve) { + throw ve; + } catch (Exception e) { + Debug.println("TurnOnSSL.applyChanges: ERROR - " + e.toString()); + } + } + } + + /** + * Validates the user choices + */ + private boolean validEntries() throws ValidationException { + String error = null; + boolean valid = true; + + // Count the problems + int howManyEnabled = 0; + int howManyNoDevice = 0; + int howManyNoCertif = 0; + + if (securitySettings.get("security").equals("on")) { + + StringTokenizer st = new StringTokenizer( (String)securitySettings.get("familyList"), ","); + if (st.countTokens() != 0) { + while (st.hasMoreTokens()) { + try { + String cipherFamily = st.nextToken(); + String val = (String)securitySettings.get(cipherFamily+"-activated"); + if ( val != null && val.equals("on") ) { + howManyEnabled++; + val = (String)securitySettings.get(cipherFamily+"-token"); + if (val == null || val.toString().length()==0) howManyNoDevice++; + val = (String)securitySettings.get(cipherFamily+"-cert"); + if (val == null || val.toString().length()==0) howManyNoCertif++; + } + + } catch(NoSuchElementException nsee) { + Debug.println("TurnOnSSL.validateEntries: Unable to read family cipher token"); + } + + + } + + } else { + Debug.println("TurnOnSSL.validateEntries: no family ciphers"); + } + + // Select the error message according to the problem + if (howManyEnabled == 0) { + valid = false; + throw new ValidationException("", _i18nMsgNoSslFamily); + } + else if (howManyNoDevice >= 1) { + valid = false; + throw new ValidationException("", _i18nMsgNoSslPreferences); + } + else if (howManyNoCertif >= 1) { + valid = false; + throw new ValidationException("", _i18nMsgNoCertificate); + } + + } else { + Debug.println(6, "TurnOnSSL.validateEntries: SSL is off"); + } + + return valid; + + } + + public void showHelp() { + Help help = new Help(_resource); + help.contextHelp("TurnOnSSL", "help"); + } + +} diff --git a/src/com/netscape/management/admserv/panel/UGDirectoryConfigPanel.java b/src/com/netscape/management/admserv/panel/UGDirectoryConfigPanel.java new file mode 100644 index 0000000..025d1a4 --- /dev/null +++ b/src/com/netscape/management/admserv/panel/UGDirectoryConfigPanel.java @@ -0,0 +1,523 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.panel; + +import java.awt.*; +import java.util.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.ConsoleInfo; +import com.netscape.management.admserv.config.*; +import com.netscape.management.nmclf.SuiConstants; +/** + * + * @version 0.1 11/23/97 + * @author miodrag@netscape.com + */ +public class UGDirectoryConfigPanel extends PluginConfigPanel implements SuiConstants { + + IConfigDataModel _configData; + + static ResourceSet _resource; + static String _i18nLdapURL, _i18nUseGlobal, _i18nOverrideGlobal; + static String _i18nBindDN, _i18nBindPW; + static String _i18nEnterBindDN, _i18nEnterBindPW; + static String _i18nHost, _i18nHostUsage, _i18nPort, _i18nUseSSL, + _i18nBaseDN, _i18nUGGroupbox; + static String _i18nEnterLdapHost, + /*_i18nEnterLdapPort,*/ _i18nEnterBaseDN, _i18nPortRange; + static String _i18nWarnCert; + + static { + _resource = new ResourceSet("com.netscape.management.admserv.panel.panel"); + _i18nLdapURL = _resource.getString("ldapds","LdapURL"); + _i18nBindDN = _resource.getString("ldapds","BindDN"); + _i18nBindPW = _resource.getString("ldapds","BindPW"); + _i18nUseGlobal = _resource.getString("ldapds","UseGlobal"); + _i18nOverrideGlobal = _resource.getString("ldapds","OverrideGlobal"); + _i18nEnterBindDN = _resource.getString("ldapds","EnterBindDN"); + _i18nEnterBindPW = _resource.getString("ldapds","EnterBindPW"); + _i18nHost = _resource.getString("ldapds","UGHost"); + _i18nHostUsage = _resource.getString("ldapds","UGHostUsage"); + _i18nPort = _resource.getString("ldapds","Port"); + _i18nUseSSL = _resource.getString("ldapds","UseSSL"); + _i18nBaseDN = _resource.getString("ldapds","BaseDN"); + _i18nUGGroupbox = _resource.getString("ldapds","UGGroupbox"); + _i18nEnterLdapHost = _resource.getString("ldapds","EnterHostPortList"); + //_i18nEnterLdapPort=_resource.getString("ldapds","EnterLdapPort"); + _i18nEnterBaseDN = _resource.getString("ldapds","EnterBaseDN"); + _i18nPortRange = _resource.getString("common","PortRange"); + _i18nWarnCert = _resource.getString("ldapds","WarnCert"); + } + + Help _help; + + JLabel _lblGlobalLdapURL, _lblGlobalLdapURLValue; + JLabel _lblBindDN, _lblBindPW1; + JRadioButton _rbUseGlobal, _rbOverrideGlobal; + JTextField _txtBindDN; + SingleBytePasswordField _txtBindPW1; + JLabel _lblHost, _lblHostUsage, _lblBaseDN; + + JTextField _txtBaseDN; + SingleByteTextField _txtHost; + JCheckBox _cbSSL; + + public UGDirectoryConfigPanel(String title, IConfigDataModel data) { + super(title); + _configData = (IConfigDataModel) data; + + setLayout(new BorderLayout()); + add(makeConfigPanel(), BorderLayout.NORTH); + _help = new Help(_resource); + } + + public void showHelp() { + _help.contextHelp("ugLdapHelp"); + } + + public IConfigDataModel getDataModel() { + return _configData; + } + + public void setDataModel(IConfigDataModel data) { + _configData = (IConfigDataModel) data; + if (_configData.isLoaded()) { + setPanelContent(_configData); + } + } + + public void initialize() throws RemoteRequestException { + if (!_configData.isLoaded()) + _configData.load(); + _rbUseGlobal.addItemListener(_rbListener); + _rbOverrideGlobal.addItemListener(_rbListener); + _cbSSL.addActionListener(_cbSSLListener); + setPanelContent(_configData); + } + + public void resetContent() { + setPanelContent(_configData); + } + + public void applyChanges() throws ConfigPanelException { + getPanelContent(_configData); + } + + public void registerEditComponents(EditMonitor editMonitor) { + //editMonitor.monitor(_txtPort); + editMonitor.monitor(_txtHost); + editMonitor.monitor(_cbSSL); + editMonitor.monitor(_txtBindDN); + editMonitor.monitor(_txtBindPW1); + editMonitor.monitor(_rbUseGlobal); + editMonitor.monitor(_rbOverrideGlobal); + } + + public void setPanelContent(IConfigDataModel data) { + + String inforef = + (String) data.getAttribute(AttrNames.UGDSCONFIG_INFOREF); + + Debug.println("inforef="+inforef); + setGlobalLdapURL( + data.getAttribute(AttrNames.UGDSCONFIG_GLOBALDIRURL)); + boolean useGlobal = inforef != null && inforef.length() > 0; + if (useGlobal) { + _rbUseGlobal.setSelected(true); + setLdapHost(""); + //setLdapPort("389"); + _cbSSL.setEnabled(false); + setBaseDN(""); + setBindDN(""); + setBindPW1(""); + } else { + _rbOverrideGlobal.setSelected(true); + setLdapURL(data.getAttribute(AttrNames.UGDSCONFIG_DIRURL)); + setBindDN(data.getAttribute(AttrNames.UGDSCONFIG_BINDDN)); + //setBindPW1(""); + setBindPW1(data.getAttribute(AttrNames.UGDSCONFIG_BINDPW)); + + } + } + + ItemListener _rbListener = new ItemListener() { + public void itemStateChanged(ItemEvent e) { + boolean enable = true; + if (e.getSource() == _rbUseGlobal && + _rbUseGlobal.isSelected()) { + enable = false; + } + _lblHost.setEnabled(enable); + _lblHost.repaint(); + _lblHostUsage.setEnabled(enable); + _lblHostUsage.repaint(); + _lblBaseDN.setEnabled(enable); + _lblBaseDN.repaint(); + _lblBindDN.setEnabled(enable); + _lblBindDN.repaint(); + _lblBindPW1.setEnabled(enable); + _lblBindPW1.repaint(); + _txtHost.setEnabled(enable); + _txtBaseDN.setEnabled(enable); + _txtBindDN.setEnabled(enable); + _txtBindPW1.setEnabled(enable); + _cbSSL.setEnabled(enable); + Color enableBackground = + UIManager.getColor(enable ? "window" : "control"); + _txtHost.setBackground(enableBackground); + _txtBaseDN.setBackground(enableBackground); + _txtBindDN.setBackground(enableBackground); + _txtBindPW1.setBackground(enableBackground); + } + }; + + ActionListener _cbSSLListener = new ActionListener() { + public void actionPerformed(ActionEvent e) { + if (_cbSSL.isSelected()) { + ; //_txtPort.setText(_defaultSSLPort); + } else { + ; //_txtPort.setText(_defaultPort); + } + } + }; + + public void setLdapHost(String host) { + _txtHost.setText((host != null) ? host : ""); + } + + /*public void setLdapPort(String port) { + _txtPort.setText((port != null) ? port : ""); + }*/ + + public void setBaseDN(String dn) { + if (dn == null) { + _txtBaseDN.setText(""); + } else if (dn.startsWith("/")) { + _txtBaseDN.setText(dn.substring(1)); + } else { + _txtBaseDN.setText(dn); + } + } + + + public void setLdapURL(String url) { + String parse; + if (url.startsWith("ldaps://")) { + _cbSSL.setSelected(true); + parse = url.substring(8); + } else if (url.startsWith("ldap://")) { + _cbSSL.setSelected(false); + parse = url.substring(7); + } else { + Debug.println("ERROR: Bad Ldap url " + url); + return; + } + + Debug.println("parse="+parse); + + // try { + // Use URL for parsing. As it does not understand LDAP protoco, set http + // java.net.URL parseurl = new java.net.URL("http" + parse); + // setLdapHost(parseurl.getHost()); + // setLdapPort(new Integer(parseurl.getPort()).toString()); + // setBaseDN(parseurl.getFile()); + // } + // catch (Exception e) { + // Debug.println("ERROR: Bad Ldap url " + url); + // return; + // } + + int iNextSlash = parse.indexOf('/', 8); + setLdapHost(parse.substring(0, iNextSlash)); + setBaseDN(parse.substring(iNextSlash + 1)); + } + + private String getLdapURL() throws ValidationException { + String host = _txtHost.getText().trim(); + String baseDN = _txtBaseDN.getText().trim(); + + if (host.length() == 0) { + throw new ValidationException("", _i18nEnterLdapHost); + } + else if (baseDN.length() == 0) { + throw new ValidationException("", _i18nEnterBaseDN); + } + + String url = _txtHost.getText().trim() + "/" + + _txtBaseDN.getText().trim(); + + if (_cbSSL.isSelected()) { + return "ldaps://" + url; + } else { + return "ldap://" + url; + } + } + + public void setGlobalLdapURL(String url) { + _lblGlobalLdapURLValue.setText((url != null) ? url : ""); + _lblGlobalLdapURLValue.repaint(); + } + + void setBindDN(String binddn) { + _txtBindDN.setText(binddn == null ? "" : binddn); + } + + void setBindPW1(String bindPW) { + _txtBindPW1.setText(bindPW == null ? "" : bindPW); + } + + public void getPanelContent(IConfigDataModel data) + throws ConfigPanelException { + if (_rbOverrideGlobal.isSelected()) { + + String url = getLdapURL(); + String bindDN = _txtBindDN.getText().trim(); + String pw1 = _txtBindPW1.getText().trim(); + boolean modified, pwdModified; + + modified = !data.getAttribute( + AttrNames.UGDSCONFIG_DIRURL).equals(""); + modified = modified || !url.equals( + data.getAttribute(AttrNames.UGDSCONFIG_DIRURL)); + modified = modified || !bindDN.equals( + data.getAttribute(AttrNames.UGDSCONFIG_BINDDN)); + modified = modified || !pw1.equals( + data.getAttribute(AttrNames.UGDSCONFIG_BINDPW)); + + if (!modified) + return; + + if (bindDN.length() == 0 && pw1.length() != 0) { + // Can not have bindPWD and not have bindDN + throw new ValidationException("", _i18nEnterBindDN); + } + + // try to connect to the server + connectAndValidate(); + + data.setAttribute(AttrNames.UGDSCONFIG_DIRURL, url); + data.setAttribute(AttrNames.UGDSCONFIG_BINDDN, bindDN); + data.setAttribute(AttrNames.UGDSCONFIG_BINDPW, pw1); + data.setAttribute(AttrNames.UGDSCONFIG_INFOREF, ""); + + } else { + data.setAttribute(AttrNames.UGDSCONFIG_INFOREF, "default"); + } + + if (data instanceof AdminConfigData) { + ((AdminConfigData) data).setDialogParent(this); // For ack dialog + } + + } + + private void connectAndValidate() throws ConfigPanelException { + String host = _txtHost.getText().trim(); + String baseDN = _txtBaseDN.getText().trim(); + String bindPWD = _txtBindPW1.getText().trim(); + String bindDN = _txtBindDN.getText().trim(); + boolean ssl = _cbSSL.isSelected(); + int portNum = -1; + + try { + LDAPUtil.validateLDAPParams(host, portNum, ssl, bindDN, + bindPWD, baseDN); + } catch (IllegalArgumentException e) { + throw new ValidationException("", e.getMessage()); + } + } + + + /** + * Override BaseEditPanel.makeConfigPanel() to provide a custom panel, + * called by baseEditPanel constructor + */ + protected JComponent makeConfigPanel() { + JPanel p = new JPanel(); + GBC gbc = new GBC(); + GridBagLayout gbl; + int row = 0; + + // Indent for the group under a radio button. + int groupIndent = 20; + + p.setBorder(BaseConfigPanel.createGroupBorder(_i18nUGGroupbox)); + p.setLayout(gbl = new GridBagLayout()); + + /** + * Create warning message for enabling SSL + */ + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, row, 3, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + p.add(createInfoMessage(), gbc); + row++; + + /** + * Create default froup + */ + _rbUseGlobal = new JRadioButton(_i18nUseGlobal, false); + gbc.setInsets(0, 0, 0, 0); + gbc.setGrid(0, row, 3, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(_rbUseGlobal, gbc); + + row++; + _lblGlobalLdapURL = new JLabel(_i18nLdapURL); + gbc.setInsets(0, groupIndent, 0, 0); + gbc.setGrid(0, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + p.add(_lblGlobalLdapURL, gbc); + + + _lblGlobalLdapURLValue = new JLabel("."); + gbc.setInsets(0, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, row, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_lblGlobalLdapURLValue, gbc); + + /** + * Create override group + */ + row++; + _rbOverrideGlobal = new JRadioButton(_i18nOverrideGlobal, false); + gbc.setInsets(DIFFERENT_COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, row, 3, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(_rbOverrideGlobal, gbc); + + row++; + _lblHost = new JLabel(_i18nHost); + gbc.setInsets(0, groupIndent, 0, 0); + gbc.setGrid(0, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + p.add(_lblHost, gbc); + + _txtHost = new SingleByteTextField(16); + gbc.setInsets(0, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, row, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_txtHost, gbc); + _lblHost.setLabelFor(_txtHost); + + row++; + + _lblHostUsage = new JLabel(_i18nHostUsage); + gbc.setInsets(0, groupIndent, 0, 0); + gbc.setGrid(0, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + p.add(_lblHostUsage, gbc); + + row++; + + _cbSSL = new JCheckBox(_i18nUseSSL, false); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, row, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + p.add(_cbSSL, gbc); + + row++; + _lblBaseDN = new JLabel(_i18nBaseDN); + _lblBaseDN.setFont(BaseConfigPanel.getLabelFont()); + gbc.setInsets(COMPONENT_SPACE, 0, 0, 0); + gbc.setGrid(0, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + p.add(_lblBaseDN, gbc); + + _txtBaseDN = new JTextField(16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, row, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_txtBaseDN, gbc); + _lblBaseDN.setLabelFor(_txtBaseDN); + + row++; + _lblBindDN = new JLabel(_i18nBindDN); + gbc.setInsets(COMPONENT_SPACE, groupIndent, 0, 0); + gbc.setGrid(0, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, // anchor + GBC.NONE); //fill + p.add(_lblBindDN, gbc); + + _txtBindDN = new JTextField(16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, row, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_txtBindDN, gbc); + _lblBindDN.setLabelFor(_txtBindDN); + + row++; + _lblBindPW1 = new JLabel(_i18nBindPW); + gbc.setInsets(COMPONENT_SPACE, groupIndent, 0, 0); + gbc.setGrid(0, row, 1, 1); + gbc.setSpace(0.0, 0.0, GBC.EAST, //GBC.EAST, // anchor + GBC.NONE); //fill + p.add(_lblBindPW1, gbc); + + _txtBindPW1 = new SingleBytePasswordField(16); + gbc.setInsets(COMPONENT_SPACE, DIFFERENT_COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, row, 2, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, // anchor + GBC.HORIZONTAL); //fill + p.add(_txtBindPW1, gbc); + _lblBindPW1.setLabelFor(_txtBindPW1); + + row++; + + ButtonGroup rbGroup = new ButtonGroup(); + rbGroup.add(_rbUseGlobal); + rbGroup.add(_rbOverrideGlobal); + + return p; + } + + private JPanel createInfoMessage() { + GridBagLayout gbl; + GBC gbc = new GBC(); + JPanel group = new JPanel(gbl = new GridBagLayout()); + int row = 0; + MultilineLabel mll; + JLabel refLabel = new JLabel(); // unsed only for font + + gbc.setInsets(0, COMPONENT_SPACE, 0, 0); + gbc.setGrid(1, row, 1, 1); + gbc.setSpace(1.0, 0.0, GBC.WEST, //anchor + GBC.HORIZONTAL); //fill + group.add(mll = new MultilineLabel(_i18nWarnCert, 1, 36), gbc); + mll.setFont(refLabel.getFont()); + row++; + + return group; + } +} diff --git a/src/com/netscape/management/admserv/panel/panel.properties b/src/com/netscape/management/admserv/panel/panel.properties new file mode 100644 index 0000000..d8c107b --- /dev/null +++ b/src/com/netscape/management/admserv/panel/panel.properties @@ -0,0 +1,264 @@ +# BEGIN COPYRIGHT BLOCK +# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. +# Copyright (C) 2005 Red Hat, Inc. +# All rights reserved. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +# + +# END COPYRIGHT BLOCK +# Admin Server Config Panel Localization file + +# +# Common Tokens +# +common-PortRange=Invalid port number.\n Port must be a number between 1 and 65535. + +# +#Help Tokens +# +networkHelp=admin +accessHelp=admin +encryptionHelp=admin +loggingHelp=admin +ldapHelp=admin +ugLdapHelp=admin +SNMPCommunityHelp=admin +SNMPManagerHelp=admin +SNMPStatusHelp=admin +editHostHelp=admin +editIPAddrHelp=admin +editSNMPCommunityHelp=admin +editSNMPManagerHelp=admin + +# +# Item Edit List +# +editlist-AddButton=&Add +editlist-EditButton=E&dit +editlist-RemoveButton=&Remove +editlist-OKButton=&OK +editlist-CancelButton=&Cancel +editlist-AddDefaultToolTip=Add +editlist-EditDefaultToolTip=Edit +editlist-RemoveDefaultToolTip=Remove +editlist-OKDefaultToolTip=OK +editlist-CancelDefaultToolTip=Cancel +editlist-HelpDefaultToolTip=Help + +# +# Status +# +status-On=ON +status-Off=OFF +status-Unknown=UNKNOWN +status-AgentOn=Master Agent is currently ON. +status-AgentOff=Master Agent is currently OFF. +status-AgentUnknown=Master Agent Status is unknown. +status-MasterAgent=Master Agent +status-Status=Status +status-CheckStatus=Chec&k Status +status-Stop=&Stop +status-Restart=&Restart +status-DialogStopAgent=Stop Master Agent +status-DialogRestartAgent=Restart Master Agent +status-DialogStatusAgent=Check Master Agent Status +status-CheckStatusToolTip=Check status of SNMP Master Agent +status-RestartToolTip=Restart SNMP Master Agent +status-StopToolTip=Stop SNMP Master Agent + + +# +# Remote operation +# +adminop-CanNotConnect=Can not connect: +adminop-Status=Status: +adminop-FailureStatus=Failure +adminop-WarningStatus=Warning +adminop-OperationDone=Done! +adminop-OperationFailed=Operation Failed! +adminop-ProgressLoading=Loading {0} ... +adminop-ProgressSaving=Saving {0} ... +adminop-LoadFailed=Failed to load the data,\nplease verify that URL is correct\nand the server is running! +adminop-SaveFailed=Failed to save the data! +adminop-NeedRestartReconnect=The adminstration server configuration has been changed\n\nFor the change to take effect, you have to restart the server and reconnect the client! +adminop-NeedRestart=The adminstration server configuration has been changed\n\nFor the change to take effect, you have to restart the server! +adminop-ServerShutdown=Can not execute the task as the Adminstration Server has been shutdown.\nNote: The server can not be started remotly from the console + +# +# Admin Config Tabbed Panel +# +config-NetworkTab=Network +config-AccessTab=Access +config-ConfigDirectoryTab=Configuration DS +config-UGDirectoryTab=User DS +config-EncryptionTab=Encryption + +# +# access panel +# +access-AdmSuperuser=Administration Server Administrator +access-UID=Username: +access-PWD=Password: +access-ConfirmPWD=Confirm Password: +access-AllowDSGW=Enable Directory Server Gateway Access +# Error messages +access-MsgEnterUID=Please enter the server admininistrator user name! +access-MsgEnterPWD=Please enter the server admininistrator password! +access-MsgPWDMismatch=The passwords do not match, please type again! + +# +# Ldap DS panel +# +ldapds-LdapURL=LDAP URL: +ldapds-BindDN=Bind DN: +ldapds-BindPW=Bind Password: +ldapds-UseGlobal=Use Default User Directory +ldapds-OverrideGlobal=Set User Directory +ldapds-EnterLdapHost=Please enter LDAP Host +ldapds-EnterLdapPort=Please enter LDAP Port Number +ldapds-EnterHostPortList=Please enter LDAP Host and Port +ldapds-EnterBaseDN=Please enter User Directory Subtree +ldapds-EnterBindDN=Please enter Directory Bind DN, or clear Bind Password +ldapds-EnterBindPW=Please enter Directory Bind Password + +ldapds-DSGroupbox=Configuration Directory +ldapds-UGGroupbox=User Directory +ldapds-DSHost=LDAP Host: +ldapds-UGHost=LDAP Host and Port: +ldapds-UGHostUsage=Example: eastcoast.example.com:389 +ldapds-Port=LDAP Port: +ldapds-UseSSL=Secure Connection +ldapds-BaseDN=User Directory Subtree: +ldapds-Changed=The Directory Server setting has been modified. +ldapds-ChangedInfo=You must shutdown and restart your Administration Server and all the\nservers in the Server Group for directory service changes to take effect. +ldapds-WarnMigrate=If you are switching to a new configuration directory, you must first migrate your server configuration from the current directory to the new one. See Directory Server documentation for more information. +ldapds-WarnCert=If you choose to use LDAP with SSL, you must first install a Trusted CA certificate for each server involved. Use the Certificate Setup Wizard to install a Trusted CA certificate. + +# +# Network panel +# +network-ProcessGroupbox=Process Settings +network-Host=Host: +network-Port=Port: +network-Address=Address: +network-IPAddr=IP Address: +network-ServerUID=Server UID: +network-HostNameFilter=Host Names to allow +network-IPAddrFilter=IP Addresses to allow +network-ConnectGroupbox=Connection Restrictions +network-EditHostDialog=Edit Host Name +network-AddHostDialog=Add Host Name +network-EditIPAddrDialog=Edit IP Address +network-AddIPAddrDialog=Add IP Address +network-HostFormat=Enter Host DNS Name\nYou can use wildcards, e.g. *.example.com +network-IPAddrFormat=Enter Host IP Address\nYou can use wildcards, e.g. 123.456.*.* +network-EditHostToolTip=Edit a Host Name +network-AddHostToolTip=Add a Host Name +network-RemoveHostToolTip=Remove a Host Name +network-EditIPToolTip=Edit an IP Address +network-AddIPToolTip=Add an IP Address +network-RemoveIPToolTip=Remove an IP Address +network-ToolTipFilterChoice=Set Connection Restrictions +network-IPAddressToolTip=Administration Server IP Address +network-PortToolTip=Administration Server Port +network-serverUIDToolTip=User ID for this Administration Server +network-HostListToolTip=List of Host Names which are allowed to connect +network-IPListToolTip=List of IP Addresses which are allowed to connect + +#Error messages +network-MsgEnterIPAddr=Please enter a valid IP Address!\nUse the format ... +network-MsgCanUseWildcards=You can use a wildcard '*' instead of +network-MsgEnterHost=Please enter a valid host DNS name! +network-MsgBadPortFormat=Bad format for the port! +network-MsgEnterServerUID=Please enter server UID + +# +# Logging panel +# +logging-LogFile=Log File: +logging-AccessLogGroupbox=Access Log +logging-ErrorLogGroupbox=Error Log + +# +# +# SNMP tabbed panel +# +snmp-CommunitiesTab=Communities +snmp-ManagersTab=Managers + +# +# +# SNMP Community panel +# +snmpcom-Description=Define Community Strings for SNMP Operations +snmpcom-DetailsGroupbox=Community Details +snmpcom-OperationsAll=GET and SET +snmpcom-OperationsGET=GET only +snmpcom-OperationsSET=SET only +snmpcom-DetailName=Community Name: +snmpcom-DetailOperations=Operations: +snmpcom-EditDialogCommunity=Community: +snmpcom-EditDialogTitle=Edit Community +snmpcom-AddDialogTitle=Add Community +snmpcom-EditDialogOperationsGroupbox=Allow operations +snmpcom-EditCommunityToolTip=Edit a Community Name +snmpcom-AddCommunityToolTip=Add a Community Name +snmpcom-RemoveCommunityToolTip=Remove a Community Name +# Error messages +snmpcom-MsgEnterCommunity=Please enter the Community name! + +# +# Snmp manager panel +# +snmpmgr-Description=Define Manager Stations that will receive traps +snmpmgr-EditDialogTitle=Edit Manager +snmpmgr-AddDialogTitle=Add Manager +snmpmgr-Manager=Manager Station: +snmpmgr-Port=Trap Port: +snmpmgr-Community=With Community: +snmpmgr-DetailsGroupbox=Manager Details +snmpmgr-EditMgrToolTip=Edit a Manager Station +snmpmgr-AddMgrToolTip=Add a Manager Station +snmpmgr-RemoveMgrToolTip=Remove a Manager Station +# Error messages +snmpmgr-MsgEnterManager=Please enter the Manager name! +snmpmgr-MsgEntryExists=Bad manager name,\nan entry with the same name already exists! +snmpmgr-MsgCanNotRename=Can not rename,\nan entry with the same name already exists! + +# +# Restart admin server +# +restart-SendRequest=Issuing restart request ... +restart-Wait=Waiting for the server to restart ... +restart-Accepted=Restart request accepted by the server. +restart-Done=The Administration Server has been restarted! +restart-Stopped=The Administration Server has been stopped!\nWaiting for the server to start ... +# +# Stop admin server +# +stop-SendRequest=Issuing shut down request ... +stop-Wait=Waiting for the server to shut down ... +stop-Accepted=Shut down request accepted by the server. +stop-Done=The Administration Server has been shut down!\nYou will not be able to start the server remotly from the console. + +# +# Encryption pane +# +TurnOnSSL-help=admin +TurnOnSSL-MsgNoSslPreferences=One of the cipher families chosen does not\nhave a token specified. +TurnOnSSL-MsgNoCertificate=One of the cipher families chosen does not\nhave a certificate specified. +TurnOnSSL-MsgNoSslFamily=To activate SSL, at least one cipher family\nmust be chosen from the cipher family list. +TurnOnSSL-Saved=The SSL setting has successfully been saved.\nPlease restart the Admin Server from the command line for the changes to take effect and then restart the Console. diff --git a/src/com/netscape/management/admserv/task/AdminTaskObject.java b/src/com/netscape/management/admserv/task/AdminTaskObject.java new file mode 100644 index 0000000..ec58a99 --- /dev/null +++ b/src/com/netscape/management/admserv/task/AdminTaskObject.java @@ -0,0 +1,96 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.task; + +import java.awt.*; +import java.util.*; +import javax.swing.*; +import com.netscape.management.admserv.*; +import com.netscape.management.client.*; +import com.netscape.management.client.util.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.acleditor.*; + +/** + * @version 0.1 11/01/97 + * @author ahakim@netscape.com + * @see ITaskObject + * @see IResourceObject + */ +public class AdminTaskObject extends TaskObject implements IResourceObject, +IMenuInfo { + static ResourceSet _resource = new ResourceSet("com.netscape.management.client.default"); + static Icon _icon = new RemoteImage("com/netscape/management/client/images/task.gif"); + static String MENU_SET_ACL = "setAcl"; + + + public Icon getIcon() { + return _icon; + } + + public Icon getLargeIcon()// NOT SUPPORTED in this case + { + return null; + } + + public void setIcon(Icon icon) { + _icon = icon; + } + + public Component getCustomPanel() { + return (Component) null; + } + + public String[] getMenuCategoryIDs() { + return new String[]{ Framework.MENU_FILE, + ResourcePage.MENU_CONTEXT }; + } + + /** + * add menu items for this page. + */ + public IMenuItem[] getMenuItems(String category) { + // for all categories, do the same thing... + return new IMenuItem[]{ new MenuItemText(MENU_SET_ACL, + _resource.getString("menu", "EditSetACL"), "TODO: description")}; + } + + /** + * Notification that a menu item has been selected. + */ + public void actionMenuSelected(IPage viewInstance, IMenuItem item) { + if (item.getID().equals(MENU_SET_ACL)) { + ConsoleInfo ci = (ConsoleInfo) getConsoleInfo().clone(); + ci.setAclDN(getConsoleInfo().getCurrentDN()); + ci.setUserGroupDN(""); + ACLEditor ed = new ACLEditor(ci); + ed.show(); + } + } + + public boolean run(IPage viewInstance, IResourceObject selection[]) { + return false; + } + + public boolean canRunSelection(IResourceObject selection[]) { + return true; + } +} diff --git a/src/com/netscape/management/admserv/task/CertSetup.java b/src/com/netscape/management/admserv/task/CertSetup.java new file mode 100644 index 0000000..da4aa75 --- /dev/null +++ b/src/com/netscape/management/admserv/task/CertSetup.java @@ -0,0 +1,66 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.task; + +import java.awt.*; +import javax.swing.*; +import com.netscape.management.admserv.*; +import com.netscape.management.client.*; +import com.netscape.management.client.security.CertificateDialog; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; +import netscape.ldap.*; + +/** + * @author schihm@netscape.com + * @author adam@netscape.com + * @author ahakim@netscape.com + * @see AdminTaskObject + */ +public class CertSetup extends AdminTaskObject { + public CertSetup() { + setName(AdminServer._resource.getString("taskName","CertSetup")); + setDescription( + AdminServer._resource.getString("taskDescription","CertSetup")); + } + + /** + * Called when user wants to execute this object, invoked by a + * double-click gesture or a menu action. In the case of multiply + * selected objects, this method is called once for each object + * (in top-bottom order). A return value of true indicates that a + * run action has been initiated, and not to call run() on other + * selected objects. + */ + public boolean run(IPage viewInstance) { + IFramework framework = viewInstance.getFramework(); + JFrame frame = framework.getJFrame(); + try { + ((Framework)framework).setBusyCursor(true); + CertificateDialog certDialog = new CertificateDialog(frame, _consoleInfo, (String)(_consoleInfo.get("SIE"))); + certDialog.show(); + } + finally { + ((Framework)framework).setBusyCursor(false); + } + return true; + } +} diff --git a/src/com/netscape/management/admserv/task/Logging.java b/src/com/netscape/management/admserv/task/Logging.java new file mode 100644 index 0000000..df727a9 --- /dev/null +++ b/src/com/netscape/management/admserv/task/Logging.java @@ -0,0 +1,68 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.task; + +import java.awt.*; +import java.util.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.admserv.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; + +/** + * + * @version 0.1 11/01/97 + * @author ahakim@netscape.com + * @see AdminTaskObject + */ +public class Logging extends AdminTaskObject { + public Logging() { + setName(AdminServer._resource.getString("taskName","logging")); + setDescription( + AdminServer._resource.getString("taskDescription","logging")); + } + + public boolean run(IPage viewInstance) { + IFramework framework = viewInstance.getFramework(); + JFrame frame = framework.getJFrame(); + + JDialog dialog = getConfigDialog(frame); + dialog.setSize(515, 425); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + return true; + } + + public JDialog getConfigDialog(Component parent) { + + DialogFrame configDialog = null; + configDialog = new DialogFrame(parent, getName(), + new BaseConfigPanel( + new LoggingConfigPanel("", _consoleInfo), + /*inDialog=*/true)); + return configDialog; + } +} diff --git a/src/com/netscape/management/admserv/task/Restart.java b/src/com/netscape/management/admserv/task/Restart.java new file mode 100644 index 0000000..210f7ae --- /dev/null +++ b/src/com/netscape/management/admserv/task/Restart.java @@ -0,0 +1,82 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.task; + +import java.awt.*; +import javax.swing.*; +import com.netscape.management.nmclf.*; +import com.netscape.management.admserv.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.client.console.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.util.*; + +/** + * + * @version 0.1 11/01/97 + * @author ahakim@netscape.com + * @see AdminTaskObject + */ +public class Restart extends AdminTaskObject { + public Restart() { + setName(AdminServer._resource.getString("taskName","restart")); + setDescription( + AdminServer._resource.getString("taskDescription","restart")); + } + + public boolean run(IPage viewInstance) { + TaskPage page = (TaskPage) viewInstance; + + if (!canRestartFromConsole(page)) + return false; + + AdminOperation operation = new RestartOperation(_consoleInfo); + operation.monitorOperation(""); + DialogFrame dialog = + new DialogFrame(page, getName(), operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + return true; + } + + private boolean canRestartFromConsole(JPanel parent) { + + IRestartControl restartControl = + (IRestartControl)_consoleInfo.get(IRestartControl.ID); + if (restartControl != null) { + if (!restartControl.canRestartFromConsole()) { + String msg = + AdminServer._resource.getString("restart","canNotRestart"); + SuiOptionPane.showMessageDialog(parent, msg, getName(), + SuiOptionPane.ERROR_MESSAGE); + return false; + } + } else { + Debug.println("RestartOperation: restart activator not in ConsoleInfo"); + } + return true; + } + + +} + diff --git a/src/com/netscape/management/admserv/task/SNMPSetup.java b/src/com/netscape/management/admserv/task/SNMPSetup.java new file mode 100644 index 0000000..e69d5f7 --- /dev/null +++ b/src/com/netscape/management/admserv/task/SNMPSetup.java @@ -0,0 +1,70 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.task; + +import java.awt.*; +import java.util.*; +import java.net.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.admserv.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; + +/** + * + * @version 0.1 12/15/97 + * @author miodrag@netscape.com + * @see AdminTaskObject + */ +public class SNMPSetup extends AdminTaskObject { + public SNMPSetup() { + setName(AdminServer._resource.getString("taskName","SNMPSetup")); + setDescription( + AdminServer._resource.getString("taskDescription","SNMPSetup")); + } + + public boolean run(IPage viewInstance) { + + IFramework framework = viewInstance.getFramework(); + JFrame frame = framework.getJFrame(); + + JDialog dialog = getConfigDialog(frame); + dialog.setSize(515, 425); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + return true; + } + + public JDialog getConfigDialog(Component parent) { + + DialogFrame configDialog = null; + configDialog = new DialogFrame(parent, getName(), + new BaseConfigPanel(new SNMPConfigPanel(_consoleInfo), + /*inDialog=*/true)); + return configDialog; + } + +} diff --git a/src/com/netscape/management/admserv/task/ServerSetup.java b/src/com/netscape/management/admserv/task/ServerSetup.java new file mode 100644 index 0000000..986a507 --- /dev/null +++ b/src/com/netscape/management/admserv/task/ServerSetup.java @@ -0,0 +1,72 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.task; + +import java.awt.*; +import java.util.*; +import java.net.*; +import java.awt.event.*; +import javax.swing.*; +import com.netscape.management.admserv.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.console.*; +import com.netscape.management.client.util.*; + +/** + * + * @version 0.1 12/15/97 + * @author miodrag@netscape.com + * @see AdminTaskObject + */ +public class ServerSetup extends AdminTaskObject { + public ServerSetup() { + setName(AdminServer._resource.getString("taskName","serverSetup")); + setDescription( + AdminServer._resource.getString("taskDescription","serverSetup")); + } + + public boolean run(IPage viewInstance) { + + IPage page = viewInstance; + IFramework framework = page.getFramework(); + JFrame frame = framework.getJFrame(); + + JDialog dialog = getConfigDialog(frame); + dialog.setSize(515, 425); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + return true; + } + + public JDialog getConfigDialog(Component parent) { + + DialogFrame configDialog = null; + String taskURL = "admin-serv/tasks/Configuration/ServerSetup"; + String adminURL = _consoleInfo.getAdminURL() + taskURL; + configDialog = new DialogFrame(parent, getName(), + new BaseConfigPanel( + new AdminConfigPanel(_consoleInfo), /*inDialog=*/true)); + return configDialog; + } +} diff --git a/src/com/netscape/management/admserv/task/Stop.java b/src/com/netscape/management/admserv/task/Stop.java new file mode 100644 index 0000000..19a749d --- /dev/null +++ b/src/com/netscape/management/admserv/task/Stop.java @@ -0,0 +1,67 @@ +/** BEGIN COPYRIGHT BLOCK + * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. + * Copyright (C) 2005 Red Hat, Inc. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * END COPYRIGHT BLOCK **/ +package com.netscape.management.admserv.task; + +import java.awt.*; +import javax.swing.*; +import com.netscape.management.nmclf.*; +import com.netscape.management.admserv.*; +import com.netscape.management.admserv.panel.*; +import com.netscape.management.client.*; +import com.netscape.management.client.console.*; +import com.netscape.management.admserv.config.*; +import com.netscape.management.client.util.*; + +/** + * + * @version 0.1 11/01/97 + * @author ahakim@netscape.com + * @see AdminTaskObject + */ +public class Stop extends AdminTaskObject { + public Stop() { + setName(AdminServer._resource.getString("taskName","stop")); + setDescription( + AdminServer._resource.getString("taskDescription","stop")); + } + + public boolean run(IPage viewInstance) { + TaskPage page = (TaskPage) viewInstance; + + String ackMsg = AdminServer._resource.getString("stop","ack"); + int userSelection = SuiOptionPane.showConfirmDialog(page, ackMsg, + getName(), SuiOptionPane.YES_NO_OPTION); + + if (userSelection != SuiOptionPane.YES_OPTION) { + return false; + } + + AdminOperation operation = new StopOperation(_consoleInfo); + operation.monitorOperation(""); + DialogFrame dialog = + new DialogFrame(page, getName(), operation.getPanel()); + dialog.setVisible(true); + dialog.dispose(); + ModalDialogUtil.sleep(); + return true; + } +} +