001/**
002 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003 *
004 * Copyright (c) 2007 Sun Microsystems Inc. All Rights Reserved
005 *
006 * The contents of this file are subject to the terms
007 * of the Common Development and Distribution License
008 * (the License). You may not use this file except in
009 * compliance with the License.
010 *
011 * You can obtain a copy of the License at
012 * https://opensso.dev.java.net/public/CDDLv1.0.html or
013 * opensso/legal/CDDLv1.0.txt
014 * See the License for the specific language governing
015 * permission and limitations under the License.
016 *
017 * When distributing Covered Code, include this CDDL
018 * Header Notice in each file and include the License file
019 * at opensso/legal/CDDLv1.0.txt.
020 * If applicable, add the following below the CDDL Header,
021 * with the fields enclosed by brackets [] replaced by
022 * your own identifying information:
023 * "Portions Copyrighted [year] [name of copyright owner]"
024 *
025 * $Id: UpgradeUtils.java,v 1.18 2009/09/30 17:35:24 goodearth Exp $
026 *
027 */
028
029/*
030 * Portions Copyrighted 2011-2013 ForgeRock, Inc.
031 */
032
033package org.forgerock.openam.upgrade;
034
035//import com.sun.identity.federation.jaxb.entityconfig.AttributeType;
036import com.iplanet.am.sdk.AMException;
037import com.sun.identity.policy.PolicyUtils;
038import com.sun.identity.shared.ldap.util.DN;
039import com.iplanet.am.util.SystemProperties;
040import com.iplanet.services.util.Crypt;
041import com.iplanet.sso.SSOException;
042import com.iplanet.sso.SSOToken;
043import com.sun.identity.authentication.internal.InvalidAuthContextException;
044import com.sun.identity.common.LDAPUtils;
045import com.sun.identity.common.configuration.ConfigurationException;
046import com.sun.identity.common.configuration.ServerConfiguration;
047import com.sun.identity.common.configuration.SiteConfiguration;
048import com.sun.identity.common.configuration.UnknownPropertyNameException;
049import com.sun.identity.security.AdminTokenAction;
050import com.sun.identity.shared.debug.Debug;
051import com.sun.identity.sm.AttributeSchema;
052import com.sun.identity.sm.AttributeSchemaImpl;
053import com.sun.identity.sm.OrganizationConfigManager;
054import com.sun.identity.sm.SMSException;
055import com.sun.identity.sm.SchemaType;
056import com.sun.identity.sm.ServiceConfig;
057import com.sun.identity.sm.ServiceConfigManager;
058import com.sun.identity.sm.ServiceManager;
059import com.sun.identity.sm.ServiceSchema;
060import com.sun.identity.sm.ServiceSchemaManager;
061import java.io.File;
062import java.io.FileInputStream;
063import java.io.FileNotFoundException;
064import java.io.FileOutputStream;
065import java.io.FileReader;
066import java.io.IOException;
067import java.security.AccessController;
068import java.util.Collections;
069import java.util.HashMap;
070import java.util.HashSet;
071import java.util.Hashtable;
072import java.util.Iterator;
073import java.util.List;
074import java.util.Map;
075import java.util.ResourceBundle;
076import java.util.Set;
077import java.util.Properties;
078import javax.security.auth.login.LoginException;
079import com.sun.identity.shared.ldap.LDAPConnection;
080import com.sun.identity.shared.ldap.LDAPException;
081import com.sun.identity.shared.ldap.util.LDIF;
082import com.sun.identity.policy.Policy;
083import com.sun.identity.policy.PolicyException;
084import com.sun.identity.policy.PolicyManager;
085import com.sun.identity.policy.Rule;
086import com.sun.identity.policy.SubjectTypeManager;
087import com.sun.identity.policy.interfaces.Condition;
088import com.sun.identity.policy.interfaces.Subject;
089import com.sun.identity.shared.Constants;
090import java.io.FileWriter;
091import java.io.BufferedReader;
092import java.io.BufferedWriter;
093import java.io.InputStreamReader;
094import java.util.Enumeration;
095import java.util.LinkedList;
096import java.util.ListIterator;
097import java.util.StringTokenizer;
098import com.sun.identity.shared.ldap.LDAPAttribute;
099import com.sun.identity.shared.ldap.LDAPAttributeSet;
100import com.sun.identity.shared.ldap.LDAPDN;
101import com.sun.identity.shared.ldap.LDAPEntry;
102import com.sun.identity.shared.ldap.LDAPSearchResults;
103import com.sun.identity.shared.ldap.LDAPSearchConstraints;
104import com.sun.identity.shared.ldap.LDAPv3;
105import com.sun.identity.shared.xml.XMLUtils;
106import com.sun.identity.sm.SMSUtils;
107import java.io.ByteArrayInputStream;
108import java.io.InputStream;
109import java.text.ParseException;
110import java.text.SimpleDateFormat;
111import java.util.ArrayList;
112import java.util.Arrays;
113import java.util.Date;
114import java.util.Locale;
115import java.util.regex.Matcher;
116import java.util.regex.Pattern;
117import org.w3c.dom.Document;
118import org.w3c.dom.Node;
119import org.w3c.dom.NodeList;
120
121/**
122 * This class contains utilities to upgrade the service schema
123 * configuration to be compatible with OpenAM.
124 *
125 * @supported.api
126 */
127public class UpgradeUtils {
128
129    private static final Pattern VERSION_FORMAT_PATTERN =
130            Pattern.compile("^(?:.*?(\\d+\\.\\d+\\.?\\d*).*)?\\((.*)\\)");
131    static Properties configTags;
132    public static final String SCHEMA_TYPE_GLOBAL = "global";
133    public static final String SCHEMA_TYPE_ORGANIZATION = "organization";
134    public static final String SCHEMA_TYPE_DYNAMIC = "dynamic";
135    public static final String SCHEMA_TYPE_USER = "user";
136    public static final String SCHEMA_TYPE_POLICY = "policy";
137    static final String AUTH_SERVICE_NAME = "iPlanetAMAuthService";
138    static final String AUTH_ATTR_NAME = "iplanet-am-auth-authenticators";
139    static final String ATTR_ADMIN_AUTH_MODULE =
140            "iplanet-am-auth-admin-auth-module";
141    static final String ATTR_ORG_AUTH_MODULE = "iplanet-am-auth-org-config";
142    static final int AUTH_SUCCESS =
143            com.sun.identity.authentication.internal.AuthContext.AUTH_SUCCESS;
144    static final String ORG_NAMING_ATTR = "o";
145    static final String OU = "ou";
146    static final String SERVICE_DN = "ou=services";
147    static final String COMMA = ",";
148    static final String EQUAL = "=";
149    static final String AUTH_CONFIG_SERVICE = "iPlanetAMAuthConfiguration";
150    static final String CONFIG_DN =
151            "ou=Configurations,ou=default,ou=OrganizationConfig,ou=1.0,";
152    static final String NAMED_CONFIG = "Configurations";
153    static final String SUB_NAMED_CONFIG = "NamedConfiguration";
154    static final String AUTH_ATTR_PREFIX = "iplanet-am-auth";
155    static final String ATTR_AUTH_CONFIG = "iplanet-am-auth-configuration";
156    static final String ATTR_AUTH_SUCCESS_URL =
157            "iplanet-am-auth-login-success-url";
158    static final String ATTR_AUTH_FAIL_URL =
159            "iplanet-am-auth-login-failure-url";
160    static final String ATTR_AUTH_POST_CLASS =
161            "iplanet-am-auth-post-login-process-class";
162    static final String START_VALUE = "<Value>";
163    static final String END_VALUE = "</Value>";
164    static final String ATTR_START_VALUE = "<AttributeValuePair>";
165    static final String ATTR_END_VALUE = "</AttributeValuePair>";
166    static final String HIDDEN_REALM =
167            "/sunamhiddenrealmdelegationservicepermissions";
168    static final String IDREPO_SERVICE = "sunIdentityRepositoryService";
169    static final String IDFF_PROVIDER_SERVICE =
170        "iPlanetAMProviderConfigService";
171    static final String IDFF_SERVICE_VERSION = "1.1";
172    static final String SERVER_HOST = "com.iplanet.am.server.host";
173    static final String SERVER_PORT = "com.iplanet.am.server.port";
174    static final String SERVER_PROTO = "com.iplanet.am.server.protocol";
175
176    static SSOToken ssoToken;
177    public static Debug debug = Debug.getInstance("amUpgrade");
178    private static boolean loggedVersionDebugMessage = false;
179    private static String dsHostName;
180    private static int dsPort;
181    private static String bindDN = null;
182    private static String bindPasswd = null;
183    private static String deployURI = null;
184    private static String dsAdminPwd;
185    private static LDAPConnection ld = null;
186    private static String basedir;
187    private static String stagingDir;
188    private static String configDir;
189    public static ResourceBundle bundle;
190    static Map entityDescriptors = new HashMap();
191    static Map entityConfigs = new HashMap();
192    // will be passed on from the main upgrade class
193    static String adminDN = null;
194    static String adminPasswd = null;
195    static String instanceType = null;
196    // the following value will be passed down from the Main Upgrade program.
197    // default dsMnanager dn.
198    static String dsManager = "cn=Directory Manager";
199    static String RESOURCE_BUNDLE_NAME = "ssoUpgrade";
200    static String PRINCIPAL = "Principal";
201    static String REALM_MODE = "realmMode";
202    static String SERVER_DEFAULTS_FILE = "serverdefaults.properties";
203    static String serverNameURL = null;
204    static final String COS_TEMPL_FILTER = "objectclass=costemplate";
205    static final String DELEGATION_SERVICE = "sunAMDelegationService";
206    static final String ORG_ADMIN_ROLE = "Organization Admin Role";
207    static final String DELEGATION_SUBJECT = "delegation-subject";
208    static final String POLICY_SERVICE = "iPlanetAMPolicyService";
209    static final String ORG_POLICY_ADMIN_ROLE =
210            "Organization Policy Admin Role";
211    static final String REALM_SERVICE = "sunAMRealmService";
212    static final String REALM_READ_ONLY = "RealmReadOnly";
213    static final String DATA_STORE_READ_ONLY = "DatastoresReadOnly";
214    static final String AM_ID_SUBJECT = "AMIdentitySubject";
215    static final String ATTR_SERVER_CONFIG = "serverconfig";
216    static final String ATTR_SERVER_CONFIG_XML = "serverconfigxml";
217    static final String CONFIG_SERVER_DEFAULT = "server-default";
218    static final String SUB_SCHEMA_SERVER = "server";
219    static final String SERVER_CONFIG_XML = "serverconfig.xml";
220    static final String BACKUP_SERVER_CONFIG_XML = "serverconfig.xml.bak";
221    static final String BACKUP_AMCONFIG = "AMConfig.properties.bak";
222    static final String ATTR_SERVER_ID = "serverid";
223    static final String ATTR_SUNSERVICE_ID = "sunserviceid";
224    static final String ATTR_SUN_KEY_VALUE = "sunkeyvalue";
225    static final String DIR_UPGRADE = "upgrade";
226    static final String DIR_CONFIG = "config";
227    static final String APPLICATION_SERVICE = "sunAMAuthApplicationService";
228    static final String POLICY_CONFIG_XML = "amPolicyConfig.xml";
229    static final String POLICY_XML = "amPolicy.xml";
230    static final String PASSWORD_RESET_XML = "amPasswordReset.xml";
231    static final String USER_XML = "amUser.xml";
232    static final String REPO_XML = "idRepoService.xml";
233    static final String UMS_XML = "ums.xml";
234    static final String UNIX_XML = "amAuthUnix.xml";
235    static final String DAI_LDIF = "FM_DAI_ds_remote_schema.ldif";
236    static final String INSTALL_LDIF = "FM_DAI_install.ldif";
237    static Hashtable propertyFileMap = new Hashtable();
238    private static final List<String> SCHEMA_ORDER = Arrays.asList(new String[]{"Global", "Organization", "Dynamic",
239        "Policy", "User", "Group", "Domain", "Generic", "PluginInterface"});
240
241    static {
242        bundle = ResourceBundle.getBundle(RESOURCE_BUNDLE_NAME);
243    }
244
245    /**
246     * Returns the SSOToken.
247     *
248     * @return Admin Token.
249     */
250    public static SSOToken getSSOToken() {
251        if (ssoToken == null) {
252            ssoToken = (SSOToken) AccessController.doPrivileged(
253                AdminTokenAction.getInstance());
254        }
255
256        return ssoToken;
257    }
258
259    /**
260     * Returns true if this version can be upgraded; automatic upgrades from 9.5
261     * onwards are supported.
262     *
263     * @return true if this instance can be upgraded
264     */
265    public static boolean canUpgrade() {
266        return true;
267    }
268
269    /**
270     * Returns true if the OpenAM version of the war file is newer than the one
271     * currently deployed.
272     *
273     * @return true if the war file version is newer than the deployed version
274     */
275    public static boolean isVersionNewer() {
276        return isVersionNewer(getCurrentVersion(), getWarFileVersion());
277    }
278
279    protected static boolean isVersionNewer(String currentVersion, String warVersion) {
280        String[] current = parseVersion(currentVersion);
281        String[] war = parseVersion(warVersion);
282        if (current == null || war == null) {
283            return false;
284        }
285        if (SystemProperties.get("org.forgerock.donotupgrade") != null) return false;
286
287        SimpleDateFormat versionDateFormat = new SimpleDateFormat(Constants.VERSION_DATE_FORMAT, Locale.UK);
288        Date currentVersionDate = null;
289        Date warVersionDate = null;
290
291        try {
292            currentVersionDate = versionDateFormat.parse(current[1]);
293            warVersionDate = versionDateFormat.parse(war[1]);
294        } catch (ParseException pe) {
295            debug.error("Unable to parse date strings; current:" + currentVersion +
296                    " war version: " + warVersion, pe);
297        }
298
299        if (currentVersionDate == null || warVersionDate == null) {
300            // stop upgrade if we cannot check
301            return false;
302        }
303
304        if (debug.messageEnabled() && !loggedVersionDebugMessage) {
305            debug.message("Current version: " + currentVersionDate);
306            debug.message("War version: " + warVersionDate);
307            // Just log once to avoid creating a large debug log file when in message mode.
308            loggedVersionDebugMessage = true;
309        }
310        boolean isBefore = currentVersionDate.before(warVersionDate);
311        if (isBefore) {
312            if (Integer.valueOf(current[0]) <= Integer.valueOf(war[0])) {
313                return true;
314            } else {
315                return false;
316            }
317        } else {
318            if (Integer.valueOf(current[0]) < Integer.valueOf(war[0])) {
319                return true;
320            } else {
321                return false;
322            }
323        }
324    }
325    public static String getCurrentVersion() {
326        return SystemProperties.get(Constants.AM_VERSION);
327    }
328
329    public static String getWarFileVersion() {
330        return ServerConfiguration.getWarFileVersion();
331    }
332
333    private static String[] parseVersion(String version) {
334        Matcher matcher = VERSION_FORMAT_PATTERN.matcher(version);
335        if (matcher.matches()) {
336            String ver = matcher.group(1);
337            if (ver == null) {
338                ver = "-1";
339            } else {
340                ver = ver.replace(".", "");
341            }
342            return new String[]{ver, matcher.group(2)};
343        }
344        return null;
345    }
346
347
348    /**
349     * Creates a new service schema in the configuration store.
350     * The service xml file passed should follow the SMS
351     * DTD.
352     *
353     * @param fileName Name of the service schema XML to be loaded.
354     * @throws UpgradeException if there is an error creating a service.
355     * @supported.api
356     */
357    public static void createService(String fileName) throws UpgradeException {
358        String classMethod = "UpgradeUtils:createService : ";
359        replaceTag(fileName, configTags);
360        if (debug.messageEnabled()) {
361            debug.message(classMethod + fileName);
362        }
363        FileInputStream fis = null;
364        try {
365            ServiceManager ssm = getServiceManager();
366            fis = new FileInputStream(fileName);
367            ssm.registerServices(fis);
368        } catch (FileNotFoundException fe) {
369            debug.error(classMethod + "File not found: " + fileName, fe);
370            throw new UpgradeException(fe.getMessage());
371        } catch (SSOException ssoe) {
372            debug.error(classMethod + "SSOToken is not valid", ssoe);
373            throw new UpgradeException(ssoe.getMessage());
374        } catch (SMSException sme) {
375            debug.error(classMethod + "Invalid service schema xml" + fileName);
376            throw new UpgradeException(sme.getMessage());
377        } finally {
378            if (fis != null) {
379                try {
380                    fis.close();
381                } catch (IOException ie) {
382                //ignore if file input stream cannot be closed.
383                }
384            }
385        }
386    }
387
388    public static void createService(String xml, SSOToken adminSSOToken)
389    throws UpgradeException {
390        String classMethod = "UpgradeUtils:createService : ";
391        InputStream serviceStream = null;
392
393        try {
394            ServiceManager serviceManager = new ServiceManager(adminSSOToken);
395
396            serviceStream = (InputStream) new ByteArrayInputStream(xml.getBytes());
397            serviceManager.registerServices(serviceStream);
398        } catch (SSOException ssoe) {
399            debug.error(classMethod + ssoe.getMessage());
400            throw new UpgradeException(ssoe);
401        } catch (SMSException smse) {
402            debug.error(classMethod + smse.getMessage());
403            throw new UpgradeException(smse);
404        } finally {
405            if (serviceStream != null) {
406                try {
407                    serviceStream.close();
408                } catch (IOException ioe) {
409                    throw new UpgradeException(ioe);
410                }
411            }
412        }
413    }
414
415    public static void modifyService(String serviceName,
416                                     Map<String, ServiceSchemaUpgradeWrapper> serviceChanges,
417                                     SSOToken adminToken)
418    throws UpgradeException {
419        for (Map.Entry<String, ServiceSchemaUpgradeWrapper> schemaMods : serviceChanges.entrySet()) {
420            ServiceSchemaUpgradeWrapper sUpdate = schemaMods.getValue();
421
422            if (sUpdate != null) {
423                if (sUpdate.getAttributesAdded() != null &&
424                        sUpdate.getAttributesAdded().hasBeenModified()) {
425                    ServiceSchema ss = getServiceSchema(serviceName, null, schemaMods.getKey(), adminToken);
426                    addAttributesToSchema(serviceName, schemaMods.getKey(), sUpdate.getAttributesAdded(), ss, adminToken);
427
428                }
429
430                if (sUpdate.getAttributesModified() != null &&
431                        sUpdate.getAttributesModified().hasBeenModified()) {
432                    ServiceSchema ss = getServiceSchema(serviceName, null, schemaMods.getKey(), adminToken);
433                    modifyAttributesInExistingSchema(serviceName, schemaMods.getKey(), sUpdate.getAttributesModified(), ss, adminToken);
434                }
435
436                if (sUpdate.getAttributesDeleted() != null &&
437                        sUpdate.getAttributesDeleted().hasBeenModified()) {
438                    ServiceSchema ss = getServiceSchema(serviceName, null, schemaMods.getKey(), adminToken);
439                    removeAttributesFromSchema(serviceName, schemaMods.getKey(), sUpdate.getAttributesDeleted(), ss, adminToken);
440                }
441            }
442        }
443    }
444
445    public static void addNewSubSchemas(String serviceName,
446                                       Map<String, SubSchemaUpgradeWrapper> subSchemaChanges,
447                                       SSOToken adminToken)
448    throws UpgradeException {
449        for (Map.Entry<String, SubSchemaUpgradeWrapper> subSchemaAdds : subSchemaChanges.entrySet()) {
450            SubSchemaUpgradeWrapper ssAdd = subSchemaAdds.getValue();
451
452            if (ssAdd != null) {
453                if (ssAdd.getSubSchemasAdded() != null &&
454                        ssAdd.getSubSchemasAdded().subSchemaChanged()) {
455                    ServiceSchema ss = getServiceSchema(serviceName, null, subSchemaAdds.getKey(), adminToken);
456                    addNewSubSchema(serviceName, ssAdd.getSubSchemasAdded(), ss, adminToken);
457                }
458            }
459        }
460    }
461
462    public static void addNewSubSchema(String serviceName,
463                                       SubSchemaModificationWrapper ssMod,
464                                       ServiceSchema serviceSchema,
465                                       SSOToken adminToken)
466    throws UpgradeException {
467        if (ssMod.hasNewSubSchema()) {
468            for (Map.Entry<String, NewSubSchemaWrapper> newSubSchema : ssMod.entrySet()) {
469                addSubSchema(serviceName, newSubSchema.getValue().getSubSchemaName(), serviceSchema, newSubSchema.getValue().getSubSchemaNode());
470
471                if (ssMod.getSubSchema().hasSubSchema()) {
472                    ServiceSchema subSchema = null;
473
474                    try {
475                        subSchema = serviceSchema.getSubSchema(newSubSchema.getKey());
476                    } catch (SMSException smse) {
477                        debug.error("unable to add new sub schema: " + newSubSchema.getKey(), smse);
478                        throw new UpgradeException(smse);
479                    }
480
481                    addNewSubSchema(serviceName, ssMod.getSubSchema(), subSchema, adminToken);
482                }
483            }
484        }
485
486
487    }
488
489    protected static void addAttributesToSchema(String serviceName,
490                                                String schemaType,
491                                                ServiceSchemaModificationWrapper schemaMods,
492                                                ServiceSchema serviceSchema,
493                                                SSOToken adminToken)
494    throws UpgradeException {
495        if (!(schemaMods.getAttributes().isEmpty())) {
496            for(AttributeSchemaImpl attrs : schemaMods.getAttributes()) {
497                    addAttributeToSchema(serviceName,
498                                         null,
499                                         schemaType,
500                                         attrs.getAttributeSchemaNode(),
501                                         adminToken);
502            }
503        }
504
505        if (schemaMods.hasSubSchema()) {
506            for (Map.Entry<String, ServiceSchemaModificationWrapper> schema : schemaMods.getSubSchemas().entrySet()) {
507                if (!(schema.getValue().getAttributes().isEmpty())) {
508                    for(AttributeSchemaImpl attrs : schema.getValue().getAttributes()) {
509                        ServiceSchema subSchema = null;
510
511                        try {
512                            subSchema = serviceSchema.getSubSchema(schema.getKey());
513                        } catch (SMSException smse) {
514                            debug.error("Unable to add attributes to schema", smse);
515                            throw new UpgradeException(smse);
516                        }
517
518                        addAttributeToSchema(subSchema, attrs.getAttributeSchemaNode());
519                    }
520                }
521
522                if (schema.getValue().hasSubSchema()) {
523                    ServiceSchema ss = null;
524
525                    try {
526                        ss = serviceSchema.getSubSchema(schema.getKey());
527                    } catch (SMSException smse) {
528                        debug.error("Unable to add attributes to schema", smse);
529                        throw new UpgradeException(smse);
530                    }
531
532                    addAttributesToSchema(serviceName, schemaType, schema.getValue(), ss, adminToken);
533                }
534            }
535        }
536    }
537
538    protected static void modifyAttributesInExistingSchema(String serviceName,
539                                                String schemaType,
540                                                ServiceSchemaModificationWrapper schemaMods,
541                                                ServiceSchema serviceSchema,
542                                                SSOToken adminToken)
543    throws UpgradeException {
544        for (AttributeSchemaImpl attrs : schemaMods.getAttributes()) {
545                modifyAttributeInExistingSchema(serviceName,
546                                     null,
547                                     schemaType,
548                                     attrs.getName(),
549                                     attrs.getAttributeSchemaNode(),
550                                     adminToken);
551        }
552
553        if (schemaMods.hasSubSchema()) {
554            for (Map.Entry<String, ServiceSchemaModificationWrapper> schema : schemaMods.getSubSchemas().entrySet()) {
555                for (AttributeSchemaImpl attrs : schema.getValue().getAttributes()) {
556                    ServiceSchema subSchema = null;
557
558                    try {
559                        subSchema = serviceSchema.getSubSchema(schema.getKey());
560                    } catch (SMSException smse) {
561                        debug.error("Unable to modify attributes in schema", smse);
562                        throw new UpgradeException(smse);
563                    }
564
565                    modifyAttributeInExistingSchema(subSchema, attrs.getName(), attrs.getAttributeSchemaNode());
566                }
567
568                if (schema.getValue().hasSubSchema()) {
569                    ServiceSchema ss = null;
570
571                    try {
572                        ss = serviceSchema.getSubSchema(schema.getKey());
573                    } catch (SMSException smse) {
574                        debug.error("Unable to modify attributes in schema", smse);
575                        throw new UpgradeException(smse);
576                    }
577
578                    modifyAttributesInExistingSchema(serviceName, schemaType, schema.getValue(), ss, adminToken);
579                }
580            }
581        }
582    }
583
584    protected static void removeAttributesFromSchema(String serviceName,
585                                                     String schemaType,
586                                                     ServiceSchemaModificationWrapper schemaMods,
587                                                     ServiceSchema serviceSchema,
588                                                     SSOToken adminToken)
589    throws UpgradeException {
590        if (!(schemaMods.getAttributes().isEmpty())) {
591            for(AttributeSchemaImpl attrs : schemaMods.getAttributes()) {
592                    removeAttributeSchema(serviceName, null, schemaType, attrs.getName(), adminToken);
593            }
594        }
595
596        if (schemaMods.hasSubSchema()) {
597            for (Map.Entry<String, ServiceSchemaModificationWrapper> schema : schemaMods.getSubSchemas().entrySet()) {
598                if (!(schema.getValue().getAttributes().isEmpty())) {
599                    for(AttributeSchemaImpl attrs : schema.getValue().getAttributes()) {
600                        ServiceSchema subSchema = null;
601
602                        try {
603                            subSchema = serviceSchema.getSubSchema(schema.getKey());
604                        } catch (SMSException smse) {
605                            debug.error("Unable to remove attributes from schema", smse);
606                            throw new UpgradeException(smse);
607                        }
608
609                        removeAttributeSchema(subSchema, attrs.getName());
610                    }
611                }
612
613                if (schema.getValue().hasSubSchema()) {
614                    ServiceSchema ss = null;
615
616                    try {
617                        ss = serviceSchema.getSubSchema(schema.getKey());
618                    } catch (SMSException smse) {
619                        debug.error("Unable to remove attributes from schema", smse);
620                        throw new UpgradeException(smse);
621                    }
622
623                    removeAttributesFromSchema(serviceName, schemaType, schema.getValue(), ss, adminToken);
624                }
625            }
626        }
627    }
628
629    public static void deleteService(String serviceName, SSOToken adminToken)
630    throws UpgradeException {
631        String classMethod = "UpgradeUtils:deleteService : ";
632
633        try {
634            ServiceManager sm = new ServiceManager(adminToken);
635            ServiceConfigManager scm = new ServiceConfigManager(
636                serviceName, adminToken);
637
638            if (scm.getGlobalConfig(null) != null) {
639                scm.removeGlobalConfiguration(null);
640            }
641
642            ServiceSchemaManager ssm = new ServiceSchemaManager(serviceName, adminToken);
643            Set<String> versions = sm.getServiceVersions(serviceName);
644
645            if (ssm.getPolicySchema() == null) {
646                if (debug.messageEnabled()) {
647                    debug.message("Service has policy schema; matching policy schema will be removed");
648                }
649
650                deletePolicyRule(serviceName, adminToken);
651            }
652
653            for (String version : versions) {
654                sm.removeService(serviceName, version);
655            }
656        } catch (SSOException ssoe) {
657            debug.error(classMethod + ssoe.getMessage());
658            throw new UpgradeException(ssoe);
659        } catch (SMSException smse) {
660            debug.error(classMethod + smse.getMessage());
661            throw new UpgradeException(smse);
662        } catch (AMException ame) {
663            debug.error(classMethod + ame.getMessage());
664            throw new UpgradeException(ame);
665        }
666    }
667
668    private static void deletePolicyRule(String serviceName, SSOToken adminToken)
669    throws SMSException, SSOException, AMException {
670        String classMethod = "UpgradeUtils:deletePolicyRule : ";
671        ServiceSchemaManager ssm = new ServiceSchemaManager(serviceName, adminToken);
672
673        if (ssm == null) {
674            if (debug.messageEnabled()) {
675                debug.message(classMethod + "delete-service-no-policy-rules");
676            }
677        } else {
678            if (ssm.getPolicySchema() == null) {
679                if (debug.messageEnabled()) {
680                    debug.message(classMethod + "delete-service-no-policy-schema");
681                }
682            } else {
683                processCleanPolicies(serviceName, adminToken);
684
685                if (debug.messageEnabled()) {
686                    debug.message(classMethod + "policy schemas cleaned");
687                }
688            }
689        }
690    }
691
692    private static void processCleanPolicies(String serviceName, SSOToken adminToken)
693    throws SMSException, SSOException, AMException {
694        PolicyUtils.removePolicyRules(adminToken, serviceName);
695    }
696
697    public static Document parseServiceFile(InputStream xml, SSOToken adminToken)
698    throws UpgradeException {
699        String classMethod = "UpgradeUtils:parseServiceFile : ";
700
701        FileInputStream fis = null;
702        Document doc = null;
703
704        try {
705            ServiceManager ssm = getServiceManager(adminToken);
706            doc = ssm.parseServicesFile(xml);
707        } catch (SSOException ssoe) {
708            debug.error(classMethod + "SSOToken is not valid", ssoe);
709            throw new UpgradeException(ssoe.getMessage());
710        } catch (SMSException sme) {
711            debug.error(classMethod + "Invalid service schema xml");
712            throw new UpgradeException(sme.getMessage());
713        } finally {
714            if (fis != null) {
715                try {
716                    fis.close();
717                } catch (IOException ie) {
718                //ignore if file input stream cannot be closed.
719                }
720            }
721        }
722
723        return doc;
724    }
725
726    public static Set<String> getExistingServiceNames(SSOToken adminToken)
727    throws UpgradeException {
728        String classMethod = "UpgradeUtils:getExistingServiceNames : ";
729        Set<String> existingServiceNames = null;
730
731        try {
732            ServiceManager sm = new ServiceManager(adminToken);
733            existingServiceNames = sm.getServiceNames();
734        } catch (SSOException ssoe) {
735            debug.error(classMethod + "SSOToken is not valid", ssoe);
736            throw new UpgradeException(ssoe.getMessage());
737        } catch (SMSException sme) {
738            debug.error(classMethod + "Invalid service schema xml");
739            throw new UpgradeException(sme.getMessage());
740        }
741
742        return existingServiceNames;
743    }
744
745    /**
746     * Adds new attribute schema to an existing service.
747     *
748     * @param serviceName the service name.
749     * @param schemaType the schema type.
750     * @param attributeSchemaNode attribute to add
751     * @param adminToken admin SSOToken
752     * @throws UpgradeException if there is an error adding the
753     *         attribute schema.
754     * @supported.api
755     */
756    public static void addAttributeToSchema(
757            String serviceName,
758            String subSchemaName,
759            String schemaType,
760            Node attributeSchemaNode,
761            SSOToken adminToken)
762    throws UpgradeException {
763        String classMethod = "UpgradeUtils:addAttributeToSchema: ";
764
765        if (debug.messageEnabled()) {
766            debug.message(classMethod + "Adding attributeschema :"
767                    + "for service :" + serviceName);
768        }
769
770        ServiceSchema ss = getServiceSchema(serviceName, subSchemaName, schemaType, adminToken);
771        ByteArrayInputStream bis = null;
772
773        try {
774            bis = new ByteArrayInputStream(XMLUtils.print(attributeSchemaNode).getBytes());
775            ss.addAttributeSchema(bis);
776        } catch (SMSException sme) {
777            debug.error(classMethod + "Cannot add attribute schema for "
778                    + serviceName, sme);
779            throw new UpgradeException(sme.getMessage());
780        } catch (SSOException ssoe) {
781            debug.error(classMethod + "Invalid SSOToken : ", ssoe);
782            throw new UpgradeException(ssoe.getMessage());
783        }
784    }
785
786    /**
787     * Adds new attribute schema to an existing service.
788     *
789     * @param serviceSchema The underlying service schema.
790     * @param attributeSchemaNode The attribute is add
791     * @throws UpgradeException if there is an error adding the
792     *         attribute schema.
793     * @supported.api
794     */
795    public static void addAttributeToSchema(ServiceSchema serviceSchema,
796            Node attributeSchemaNode)
797    throws UpgradeException {
798        String classMethod = "UpgradeUtils:addAttributeToSchema: ";
799
800        if (debug.messageEnabled()) {
801            debug.message(classMethod + "Adding attributeschema :"
802                    + "for service :" + serviceSchema.getName());
803        }
804
805        ByteArrayInputStream bis = null;
806
807        try {
808            bis = new ByteArrayInputStream(XMLUtils.print(attributeSchemaNode).getBytes());
809            serviceSchema.addAttributeSchema(bis);
810        } catch (SMSException sme) {
811            debug.error(classMethod + "Cannot add attribute schema for "
812                    + serviceSchema.getName(), sme);
813            throw new UpgradeException(sme.getMessage());
814        } catch (SSOException ssoe) {
815            debug.error(classMethod + "Invalid SSOToken : ", ssoe);
816            throw new UpgradeException(ssoe.getMessage());
817        }
818    }
819
820    /**
821     * Adds new attribute schema to a sub schema in an existing service.
822     *
823     * @param serviceName the service name.
824     * @param subSchemaName the sub schema name.
825     * @param schemaType the schema type.
826     * @param attributeSchemaFile
827     *         XML file containing attribute schema definition.
828     * @throws UpgradeException if there is an error adding the
829     *         attribute schema.
830     * @supported.api
831     */
832    public static void addAttributeToSubSchema(
833            String serviceName,
834            String subSchemaName,
835            String schemaType,
836            String attributeSchemaFile) throws UpgradeException {
837        String classMethod = "UpgradeUtils:addAttributeToSubSchema : ";
838        if (debug.messageEnabled()) {
839            debug.message(classMethod + "Adding attribute schema : "
840                    + attributeSchemaFile);
841            debug.message(" to subSchema " + subSchemaName +
842                    " to service " + serviceName);
843        }
844        FileInputStream fis = null;
845        ServiceSchema ss =
846                getServiceSchema(serviceName, subSchemaName, schemaType);
847        try {
848            fis = new FileInputStream(attributeSchemaFile);
849            ss.addAttributeSchema(fis);
850        } catch (IOException ioe) {
851            debug.error(classMethod + "File not found " + attributeSchemaFile);
852            throw new UpgradeException(ioe.getMessage());
853        } catch (SMSException sme) {
854            debug.error(classMethod + "Cannot add attribute schema to : "
855                    + serviceName, sme);
856            throw new UpgradeException(sme.getMessage());
857        } catch (SSOException ssoe) {
858            debug.error(classMethod + "Invalid SSOToken : ", ssoe);
859            throw new UpgradeException(ssoe.getMessage());
860        } catch (Exception e ) {
861            debug.error(classMethod + "Error setting attribute schema : ", e);
862            throw new UpgradeException(e.getMessage());
863        }
864    }
865
866    public static void modifyAttributeInExistingSchema(
867            String serviceName,
868            String subSchemaName,
869            String schemaType,
870            String attrName,
871            Node attributeSchemaNode,
872            SSOToken adminToken)
873    throws UpgradeException {
874        String classMethod = "UpgradeUtils:modifyAttributeInExistingSchema: ";
875
876        if (debug.messageEnabled()) {
877            debug.message(classMethod + "Modifying attributeschema :"
878                    + "for service :" + serviceName);
879        }
880
881        removeAttributeSchema(serviceName, subSchemaName, schemaType, attrName, adminToken);
882        addAttributeToSchema(serviceName,
883                             subSchemaName,
884                             schemaType,
885                             attributeSchemaNode,
886                             adminToken);
887    }
888
889    public static void modifyAttributeInExistingSchema(ServiceSchema serviceSchema,
890            String attrName, Node attributeSchemaNode)
891    throws UpgradeException {
892        String classMethod = "UpgradeUtils:modifyAttributeInExistingSchema: ";
893
894        if (debug.messageEnabled()) {
895            debug.message(classMethod + "Modifying attributeschema :"
896                    + "for service :" + serviceSchema.getName());
897        }
898
899        removeAttributeSchema(serviceSchema, attrName);
900        addAttributeToSchema(serviceSchema, attributeSchemaNode);
901    }
902
903    /**
904     * Sets default values of an existing attribute.
905     * The existing values will be overwritten with the new values.
906     *
907     * @param serviceName name of the service
908     * @param subSchemaName name of the subschema
909     * @param schemaType the type of schema.
910     * @param attributeName name of the attribute
911     * @param defaultValues a set of values to be added to the attribute
912     * @throws UpgradeException if there is an error.
913     * @supported.api
914     */
915    public static void setAttributeDefaultValues(
916            String serviceName,
917            String subSchemaName,
918            String schemaType,
919            String attributeName,
920            Set defaultValues) throws UpgradeException {
921        String classMethod = "UpgradeUtils:setAttributeDefaultValues : ";
922        if (debug.messageEnabled()) {
923            debug.message(classMethod + " for attribute :" + attributeName +
924                    "in service :" + serviceName);
925        }
926        ServiceSchema ss =
927                getServiceSchema(serviceName, subSchemaName, schemaType);
928        try {
929            ss.setAttributeDefaults(attributeName, defaultValues);
930        } catch (SSOException ssoe) {
931            debug.error(classMethod + "Invalid SSOToken", ssoe);
932            throw new UpgradeException(bundle.getString("invalidSSOToken"));
933        } catch (SMSException sme) {
934            debug.error("Unable to set default values for attribute " +
935                    attributeName + " in service :" + serviceName, sme);
936            throw new UpgradeException(sme.getMessage());
937        }
938    }
939
940    /**
941     * Adds default values to an existing attribute.
942     * The existing values in the attribute will be updated with new values.
943     *
944     * @param serviceName name of the service
945     * @param subSchemaName name of the subschema
946     * @param schemaType the schemaType
947     * @param attributeName name of the attribute
948     * @param defaultValues a set of values to be added to the attribute
949     * @throws <code>UpgradeException</code> if there is an error.
950     * @supported.api
951     */
952    public static void addAttributeDefaultValues(
953            String serviceName,
954            String subSchemaName,
955            String schemaType,
956            String attributeName,
957            Set defaultValues) throws UpgradeException {
958        String classMethod = "UpgradeUtils:addAttributeDefaultValues : ";
959        if (debug.messageEnabled()) {
960            debug.message(classMethod + "Updating attribute default values");
961            debug.message("in :" + serviceName +
962                    "for attribute: " + attributeName);
963        }
964        ServiceSchema ss =
965                getServiceSchema(serviceName, subSchemaName, schemaType);
966        try {
967            Map attributeDefaults = ss.getAttributeDefaults();
968            Set oldAttrValues = (Set) attributeDefaults.get(attributeName);
969            Set newAttrValues =
970                    ((oldAttrValues == null) || oldAttrValues.isEmpty())
971                    ? new HashSet() : new HashSet(oldAttrValues);
972            newAttrValues.addAll(defaultValues);
973            ss.setAttributeDefaults(attributeName, newAttrValues);
974        } catch (SSOException ssoe) {
975            throw new UpgradeException("Invalid SSOToken");
976        } catch (SMSException sme) {
977            throw new UpgradeException("Failed to add attribute default " +
978                    "values");
979        }
980    }
981    /**
982     * Add attribute choice values to an existing attribute.
983     * The existing attribute values will be updated with new choice values.
984     *
985     * @param serviceName name of the service
986     * @param subSchemaName name of the subschema
987     * @param schemaType the schemaType
988     * @param attributeName name of the attribute
989     * @param choiceValuesMap a set of choice values values to
990     *        be added to the attribute, the key is the i18NKey and
991     *        the values it the choice value
992     * @throws <code>UpgradeException</code> if there is an error.
993     */
994
995    public static void addAttributeChoiceValues(
996            String serviceName,
997            String subSchemaName,
998            String schemaType,
999            String attributeName,
1000            Map choiceValuesMap)
1001            throws UpgradeException {
1002        String classMethod = "UpgradeUtils.addAttributeChoiceValues";
1003        try {
1004            ServiceSchema ss =
1005                    getServiceSchema(serviceName, subSchemaName, schemaType);
1006            AttributeSchema attrSchema = ss.getAttributeSchema(attributeName);
1007            addChoiceValues(attrSchema, choiceValuesMap);
1008        } catch (SSOException ssoe) {
1009            throw new UpgradeException(classMethod + " Error getting SSOToken ");
1010        } catch (SMSException sme) {
1011            throw new UpgradeException(classMethod + " Error updating choice values ");
1012        }
1013    }
1014
1015    /**
1016     * Add choice values to an attribute .
1017     */
1018    protected static void addChoiceValues(
1019            AttributeSchema attrSchema,
1020            Map choiceValMap) throws SMSException, SSOException {
1021        for (Iterator i = choiceValMap.keySet().iterator(); i.hasNext();) {
1022            String i18nKey = (String) i.next();
1023            Set valueSet = (Set) choiceValMap.get(i18nKey);
1024            String value = (String) valueSet.iterator().next();
1025            attrSchema.addChoiceValue(value, i18nKey);
1026        }
1027    }
1028
1029    /**
1030     * Remove an attribute schema from an existing service.
1031     *
1032     * @param serviceName the service name.
1033     * @param subSchemaName name of the subschema
1034     * @param schemaType the schema type.
1035     * @param attributeName attribute to remove
1036     * @param adminToken admin SSOToken
1037     * @throws UpgradeException if there is an error adding the
1038     *         attribute schema.
1039     * @supported.api
1040     */
1041    public static void removeAttributeSchema(
1042            String serviceName,
1043            String subSchemaName,
1044            String schemaType,
1045            String attributeName,
1046            SSOToken adminToken)
1047    throws UpgradeException {
1048        String classMethod = "UpgradeUtils:removeAttributeSchema: ";
1049
1050        if (debug.messageEnabled()) {
1051            debug.message(classMethod + "Removing attribute :" + attributeName
1052                    + " from service :" + serviceName);
1053        }
1054
1055        ServiceSchema ss = getServiceSchema(serviceName, subSchemaName, schemaType, adminToken);
1056
1057        try {
1058            ss.removeAttributeSchema(attributeName);
1059        } catch (SMSException sme) {
1060            debug.error(classMethod + "Cannot remove attribute schema for "
1061                    + serviceName, sme);
1062            throw new UpgradeException(sme.getMessage());
1063        } catch (SSOException ssoe) {
1064            debug.error(classMethod + "Invalid SSOToken : ", ssoe);
1065            throw new UpgradeException(ssoe.getMessage());
1066        }
1067    }
1068
1069    /**
1070     * Removes attribute schema from an existing service.
1071     *
1072     * @param serviceSchema The underlying service schema.
1073     * @param attributeName The attribute is add
1074     * @throws UpgradeException if there is an error adding the
1075     *         attribute schema.
1076     * @supported.api
1077     */
1078    public static void removeAttributeSchema(ServiceSchema serviceSchema,
1079            String attributeName)
1080    throws UpgradeException {
1081        String classMethod = "UpgradeUtils:removeAttributeFromSchema: ";
1082
1083        if (debug.messageEnabled()) {
1084            debug.message(classMethod + "Removing attributeschema : " + attributeName
1085                    + "from service :" + serviceSchema.getName());
1086        }
1087
1088        try {
1089            serviceSchema.removeAttributeSchema(attributeName);
1090        } catch (SMSException sme) {
1091            debug.error(classMethod + "Cannot remove attribute schema for "
1092                    + serviceSchema.getName(), sme);
1093            throw new UpgradeException(sme.getMessage());
1094        } catch (SSOException ssoe) {
1095            debug.error(classMethod + "Invalid SSOToken : ", ssoe);
1096            throw new UpgradeException(ssoe.getMessage());
1097        }
1098    }
1099
1100    /**
1101     * Sets the I18N File Name .
1102     *
1103     * @param serviceName name of the service.
1104     * @param value the i18NFileName attribute value.
1105     * @throws <code>UpgradeException</code> when there is an error.
1106     */
1107    public static void seti18NFileName(
1108            String serviceName,
1109            String value) throws UpgradeException {
1110        String classMethod = "UpgradeUtils:seti18NFileName : ";
1111        try {
1112            ServiceSchemaManager ssm = getServiceSchemaManager(serviceName);
1113            ssm.setI18NFileName(value);
1114            if (debug.messageEnabled()) {
1115                debug.message(classMethod + serviceName +
1116                    " :Setting I18NFileName " + value);
1117            }
1118        } catch (SSOException ssoe) {
1119            throw new UpgradeException("Invalid SSOToken ");
1120        } catch (SMSException sme) {
1121            throw new UpgradeException("Error setting i18NFileName value");
1122        }
1123    }
1124
1125    /**
1126     * Sets the service revision number.
1127     *
1128     * @param serviceName name of the service.
1129     * @param revisionNumber the revisionNumber of the service.
1130     * @throws <code>UpgradeException</code> if there is an error.
1131     */
1132    public static void setServiceRevision(
1133            String serviceName,
1134            String revisionNumber) throws UpgradeException {
1135        String classMethod = "UpgradeUtils:setServiceRevision : ";
1136        try {
1137            System.out.println(bundle.getString("upg-service-name") + ":"
1138                + serviceName);
1139            System.out.println(bundle.getString("upg-revision-number")
1140                + ":" + revisionNumber);
1141            if (debug.messageEnabled()) {
1142                debug.message("Setting service revision for :" + serviceName
1143                    + "to : " + revisionNumber);
1144            }
1145            ServiceSchemaManager ssm = getServiceSchemaManager(serviceName);
1146            ssm.setRevisionNumber(Integer.parseInt(revisionNumber));
1147            if (debug.messageEnabled()) {
1148                debug.message(classMethod + serviceName +
1149                        ":Setting Service Revision Number" + revisionNumber);
1150            }
1151        } catch (SSOException ssoe) {
1152            throw new UpgradeException("Invalid SSOToken ");
1153        } catch (SMSException sme) {
1154            throw new UpgradeException("Error setting serviceRevision value");
1155        }
1156    }
1157
1158    /**
1159     * Updates the values of the <code>any</code> attribute in the attribute
1160     * schema.
1161     *
1162     * @param serviceName the service name where the attribute exists.
1163     * @param subSchema the subschema name.
1164     * @param schemaType the schema type
1165     * @param attrName the attribute name.
1166     * @param value the value of the <code>any</code> attribute
1167     * @throws UpgradeException if there is an error.
1168     */
1169    public static void modifyAnyInAttributeSchema(
1170            String serviceName,
1171            String subSchema,
1172            String schemaType,
1173            String attrName,
1174            String value) throws UpgradeException {
1175        try {
1176            ServiceSchema ss =
1177                    getServiceSchema(serviceName, subSchema, schemaType);
1178            AttributeSchema attrSchema = ss.getAttributeSchema(attrName);
1179            attrSchema.setAny(value);
1180        } catch (SSOException ssoe) {
1181            throw new UpgradeException("Invalid token");
1182        } catch (SMSException sme) {
1183            throw new UpgradeException("Error setting any attribute");
1184        }
1185    }
1186
1187    /**
1188     * Updates the values of the <code>i18NKey</code> attribute in the service`
1189     * subschema.
1190     *
1191     * @param serviceName the service name where the attribute exists.
1192     * @param subSchema the subschema name.
1193     * @param schemaType the schema type
1194     * @param i18NKeyValue the value of the <code>i18NKey</code> attribute
1195     * @throws UpgradeException if there is an error.
1196     */
1197    public static void modifyI18NKeyInSubSchema(
1198            String serviceName,
1199            String subSchema,
1200            String schemaType,
1201            String i18NKeyValue) throws UpgradeException {
1202        String classMethod = "UpgradeUtils:modifyI18NKeyInSubSchema : ";
1203        try {
1204            ServiceSchema ss =
1205                    getServiceSchema(serviceName, subSchema, schemaType);
1206            ss.setI18Nkey(i18NKeyValue);
1207        } catch (SSOException ssoe) {
1208            debug.error(classMethod + "Invalid SSOToken");
1209            throw new UpgradeException("Invalid SSOToken");
1210        } catch (SMSException sme) {
1211            debug.error(classMethod +
1212                    "Error setting i18N key : " + serviceName,sme);
1213            throw new UpgradeException("Error setting i18NKey Value");
1214        }
1215    }
1216
1217    /**
1218     * Returns the current service revision number .
1219     *
1220     * @param serviceName name of the service.
1221     * @return revisionNumber the service revision number.
1222     */
1223    public static int getServiceRevision(String serviceName) {
1224        int revisionNumber = -1;
1225        ServiceSchemaManager ssm = getServiceSchemaManager(serviceName);
1226        if (ssm != null) {
1227            revisionNumber = ssm.getRevisionNumber();
1228        }
1229        return revisionNumber;
1230    }
1231
1232    /**
1233     * Returns true if the value of realmMode attribute is true.
1234     * If there is an error retrieving the attribute a false will be
1235     * assumed.
1236     *
1237     * @return true if realmMode attribute value is true otherwise false.
1238     */
1239    public static boolean isRealmMode() {
1240        String classMethod = "UpgradeUtils:isRealmMode";
1241        boolean isRealmMode = false;
1242        getSSOToken();
1243        try {
1244            ServiceSchemaManager sm = getServiceSchemaManager(IDREPO_SERVICE);
1245            ServiceSchema ss = sm.getSchema(SCHEMA_TYPE_GLOBAL);
1246            Map attributeDefaults = ss.getAttributeDefaults();
1247            if (attributeDefaults.containsKey(REALM_MODE)) {
1248                HashSet hashSet = (HashSet) attributeDefaults.get(REALM_MODE);
1249                String value = (String) (hashSet.iterator().next());
1250                if (debug.messageEnabled()) {
1251                    debug.message("realmMode is : " + value);
1252                }
1253                if (value != null && value.equalsIgnoreCase("true")) {
1254                    isRealmMode = true;
1255                }
1256            }
1257        } catch (Exception e) {
1258            debug.error(classMethod + "Error retreiving the attribute", e);
1259        }
1260        return isRealmMode;
1261    }
1262
1263    /**
1264     * Removes choice values from attribute schema.
1265     *
1266     * @param serviceName Name of service.
1267     * @param schemaType Type of schema.
1268     * @param attributeName Name of attribute.
1269     * @param choiceValues Choice values e.g. Inactive
1270     * @param subSchema Name of sub schema.
1271     * @throws UpgradeException if there is an error.
1272     */
1273    public static void removeAttributeChoiceValues(
1274            String serviceName,
1275            String schemaType,
1276            String attributeName,
1277            Set choiceValues,
1278            String subSchema) throws UpgradeException {
1279        try {
1280            ServiceSchema ss =
1281                    getServiceSchema(serviceName, subSchema, schemaType);
1282            AttributeSchema attrSchema =
1283                    ss.getAttributeSchema(attributeName);
1284            for (Iterator i = choiceValues.iterator(); i.hasNext();) {
1285                String choiceValue = (String) i.next();
1286                attrSchema.removeChoiceValue(choiceValue);
1287            }
1288        } catch (SSOException ssoe) {
1289            throw new UpgradeException("Invalid SSOToken");
1290        } catch (SMSException sme) {
1291            throw new UpgradeException("Error removing attribute choice vals");
1292        }
1293    }
1294
1295    /**
1296     * Removes attributes default values.
1297     *
1298     * @param serviceName name of the service
1299     * @param schemaType the schema type
1300     * @param attributeName name of the attribute
1301     * @param defaultValues a set of values to be removed
1302     * @param subSchema name of the sub schema
1303     * @throws UpgradeException if there is an error
1304     */
1305    public static void removeAttributeDefaultValues(
1306            String serviceName,
1307            String schemaType,
1308            String attributeName,
1309            Set defaultValues,
1310            String subSchema) throws UpgradeException {
1311        String classMethod = "UpgradeUtils:removeAttributeDefaultValues : ";
1312        try {
1313            ServiceSchema ss =
1314                    getServiceSchema(serviceName, subSchema, schemaType);
1315            // check if service schema exists.
1316            if (ss != null) {
1317                AttributeSchema attrSchema =
1318                        ss.getAttributeSchema(attributeName);
1319                for (Iterator i = defaultValues.iterator(); i.hasNext();) {
1320                    String defaultValue = (String) i.next();
1321                    attrSchema.removeDefaultValue(defaultValue);
1322                }
1323            }
1324        } catch (SSOException ssoe) {
1325            throw new UpgradeException("Invalid SSOToken");
1326        } catch (SMSException sme) {
1327            throw new UpgradeException("Error removing attribute" +
1328                    " default vals");
1329        } catch (Exception e) {
1330            UpgradeUtils.debug.error(classMethod +
1331                    "Error removing attribute default vals", e);
1332            throw new UpgradeException("Error removing attribute" +
1333                    " default values");
1334        }
1335    }
1336
1337    /**
1338     * Adds sub schema to a service.
1339     *
1340     * @param serviceName Name of service.
1341     * @param subSchema the subschema name.
1342     * @param schemaType the schema type.
1343     * @param fileName Name of file that contains the sub schema
1344     * @throws UpgradeException if there is an error
1345     */
1346    public static void addSubSchema(
1347            String serviceName,
1348            String subSchema,
1349            String schemaType,
1350            String fileName) throws UpgradeException {
1351        String classMethod = "UpgradeUtils:addSubSchema : ";
1352        if (debug.messageEnabled()) {
1353            debug.message(classMethod + "Adding subschema: " +
1354                fileName + " for service: " + serviceName);
1355        }
1356        try {
1357            ServiceSchema ss =
1358                    getServiceSchema(serviceName, subSchema, schemaType);
1359            ss.addSubSchema(new FileInputStream(fileName));
1360        } catch (IOException ioe) {
1361            throw new UpgradeException("Error reading schema file ");
1362        } catch (SSOException ssoe) {
1363            throw new UpgradeException("invalid sso token");
1364        } catch (SMSException ssoe) {
1365            throw new UpgradeException("error creating subschema");
1366        }
1367    }
1368
1369    /**
1370     * Adds sub schema to a service.
1371     *
1372     * @param serviceName Name of service.
1373     * @param subSchemaName the subschema name.
1374     * @param serviceSchema the underlying service schema
1375     * @param subSchemaNode the subschema
1376     * @throws UpgradeException if there is an error
1377     */
1378    public static void addSubSchema(
1379            String serviceName,
1380            String subSchemaName,
1381            ServiceSchema serviceSchema,
1382            Node subSchemaNode)
1383    throws UpgradeException {
1384        String classMethod = "UpgradeUtils:addSubSchema : ";
1385
1386        if (debug.messageEnabled()) {
1387            debug.message(classMethod + "Adding subschema:" +
1388                subSchemaName + " for service: " + serviceName);
1389        }
1390
1391        ByteArrayInputStream bis = null;
1392
1393        try {
1394            bis = new ByteArrayInputStream(XMLUtils.print(subSchemaNode).getBytes());
1395            serviceSchema.addSubSchema(bis);
1396        } catch (SSOException ssoe) {
1397            throw new UpgradeException("invalid sso token");
1398        } catch (SMSException ssoe) {
1399            throw new UpgradeException("error creating subschema");
1400        }
1401    }
1402
1403    /**
1404     * Adds SubConfiguration to a service.
1405     *
1406     * @param serviceName the service name
1407     * @param svcConfigName the service config
1408     * @param subConfigName the subconfig name
1409     * @param subConfigID the subconfig id
1410     * @param attrValues a map of attribute value pairs to be added to the
1411     *        subconfig.
1412     * @param priority the priority value
1413     * @throws UpgradeException if there is an error.
1414     */
1415    public static void addSubConfiguration(
1416            String serviceName,
1417            String svcConfigName,
1418            String subConfigName,
1419            String subConfigID,
1420            Map attrValues, int priority) throws UpgradeException {
1421        String classMethod = "UpgradeUtils:addSubConfiguration";
1422        try {
1423            ServiceConfigManager scm =
1424                    new ServiceConfigManager(serviceName, ssoToken);
1425            ServiceConfig sc = scm.getGlobalConfig(null);
1426            if (sc != null) {
1427                sc.addSubConfig(subConfigName, subConfigID,
1428                        priority, attrValues);
1429            } else {
1430                debug.error(classMethod + "Error adding sub cofiguration " + subConfigName);
1431                throw new UpgradeException("Error adding subconfig");
1432            }
1433        } catch (SSOException ssoe) {
1434            throw new UpgradeException("invalid sso token");
1435        } catch (SMSException sm) {
1436            debug.error(classMethod + "Error loading subconfig", sm);
1437            throw new UpgradeException("error adding subconfig");
1438        }
1439    }
1440
1441    /**
1442     * Loads the ldif changes to the directory server.
1443     *
1444     * @param ldifFileName the name of the ldif file.
1445     */
1446    public static void loadLdif(String ldifFileName) {
1447        String classMethod = "UpgradeUtils:loadLdif : ";
1448        try {
1449            System.out.println(bundle.getString("upg-load-ldif-file")
1450                + " :" + ldifFileName);
1451            LDIF ldif = new LDIF(ldifFileName);
1452            ld = getLDAPConnection();
1453            LDAPUtils.createSchemaFromLDIF(ldif, ld);
1454        } catch (IOException ioe) {
1455            debug.error(classMethod +
1456                    "Cannot find file . Error loading ldif"+ldifFileName,ioe);
1457        } catch (LDAPException le) {
1458            debug.error(classMethod + "Error loading ldif" +ldifFileName,le);
1459        }
1460    }
1461
1462    /**
1463     * Helper method to return Ldap connection
1464     *
1465     * @return Ldap connection
1466     */
1467    private static LDAPConnection getLDAPConnection() {
1468        String classMethod = "UpgradeUtils:getLDAPConnection : ";
1469        if (debug.messageEnabled()) {
1470            debug.message(classMethod + "Directory Server Host: " + dsHostName);
1471            debug.message(classMethod + "Directory Server Port: " + dsPort);
1472            debug.message(classMethod + "Direcotry Server DN: " + dsManager);
1473        }
1474        if (ld == null) {
1475            try {
1476                ld = new LDAPConnection();
1477                ld.setConnectTimeout(300);
1478                ld.connect(3, dsHostName, dsPort, dsManager, dsAdminPwd);
1479            } catch (LDAPException e) {
1480                disconnectDServer();
1481                ld = null;
1482                debug.error(classMethod + " Error getting LDAP Connection");
1483            }
1484        }
1485        return ld;
1486    }
1487
1488    /**
1489     * Helper method to disconnect from Directory Server.
1490     */
1491    private static void disconnectDServer() {
1492        if ((ld != null) && ld.isConnected()) {
1493            try {
1494                ld.disconnect();
1495                ld = null;
1496            } catch (LDAPException e) {
1497                debug.error("Error disconnecting ", e);
1498            }
1499        }
1500    }
1501
1502
1503// Legacy code to support older upgrade data based on amAdmin dtd.
1504// These should not be used for the new data since these will be
1505// deprecated along with amAdmin.
1506// therefore not adding public javadocs for these.
1507    /**
1508     * Imports service data.
1509     * @param fileName the file containing the data in xml format.
1510     * @throws <code>UpgradeException</code> on error
1511     */
1512    public static void importServiceData(
1513            String fileName)
1514            throws UpgradeException {
1515        System.out.println(bundle.getString("upg-import-service-data")
1516            + ": " + fileName);
1517        String[] args = new String[8];
1518        args[0] = "--runasdn";
1519        args[1] = bindDN;
1520        args[2] = "-w";
1521        args[3] = bindPasswd;
1522        args[4] = "-c";
1523        args[5] = "-v";
1524        args[6] = "-t";
1525        args[7] = fileName;
1526        invokeAdminCLI(args);
1527    }
1528
1529    /**
1530     * Imports service data
1531     *
1532     * @param fileList list of files to be imported.
1533     * @throws UpgradeException on error.
1534     */
1535    public static void importServiceData(
1536            String[] fileList) throws UpgradeException {
1537        System.out.println(bundle.getString("upg-import-service-data")
1538                           + fileList);
1539        int len = fileList.length;
1540        String[] args = new String[7 + len];
1541        args[0] = "--runasdn";
1542        args[1] = bindDN;
1543        args[2] = "-w";
1544        args[3] = bindPasswd;
1545        args[4] = "-c";
1546        args[5] = "-v";
1547        args[6] = "-t";
1548        System.arraycopy(fileList, 0, args, 7, len);
1549        invokeAdminCLI(args);
1550    }
1551
1552    /**
1553     * Imports service data
1554     *
1555     * @param fileList list of files to be imported.
1556     * @throws UpgradeException
1557     */
1558    public static void importServiceData(List<String> fileList)
1559            throws UpgradeException {
1560        String classMethod = "UpgradeUtils:importServiceData : ";
1561        if (debug.messageEnabled()) {
1562            debug.message(classMethod + "Import Service Data :" + fileList);
1563        }
1564        System.out.println(bundle.getString("upg-import-service-data")
1565                           + fileList);
1566        int len = fileList.size();
1567        String[] args = new String[7 + len];
1568        args[0] = "--runasdn";
1569        args[1] = bindDN;
1570        args[2] = "-w";
1571        args[3] = bindPasswd;
1572        args[4] = "-c";
1573        args[5] = "-v";
1574        args[6] = "-t";
1575
1576        for (int i = 0; i < len; i++) {
1577            args[7 + i] = fileList.get(i);
1578        }
1579        invokeAdminCLI(args);
1580    }
1581
1582    /**
1583     * Imports new service schema.
1584     *
1585     * @param fileList list of files to be imported.
1586     * @throws UpgradeException on error.
1587     */
1588    public static void importNewServiceSchema(
1589            String[] fileList) throws UpgradeException {
1590
1591        int len = fileList.length;
1592        String[] args = new String[7 + len];
1593        args[0] = "--runasdn";
1594        args[1] = bindDN;
1595        args[2] = "-w";
1596        args[3] = bindPasswd;
1597        args[4] = "-c";
1598        args[5] = "-v";
1599        args[6] = "-s";
1600        System.arraycopy(fileList, 0, args, 7, len);
1601        invokeAdminCLI(args);
1602    }
1603
1604    /**
1605     * Import new service schema
1606     *
1607     * @param fileName name of the file to be imported.
1608     * @throws UpgradeException on error.
1609     */
1610    public static void importNewServiceSchema(
1611            String fileName) throws UpgradeException {
1612        String[] args = new String[8];
1613        args[0] = "--runasdn";
1614        args[1] = bindDN;
1615        args[2] = "-w";
1616        args[3] = bindPasswd;
1617        args[4] = "-c";
1618        args[5] = "-v";
1619        args[6] = "-s";
1620        args[7] = fileName;
1621        invokeAdminCLI(args);
1622    }
1623
1624    /**
1625     * Imports new service schema.
1626     *
1627     * @param fileList list of files
1628     * @throws UpgradeException
1629     */
1630    public static void importNewServiceSchema(
1631            List<String> fileList) throws UpgradeException {
1632        int len = fileList.size();
1633        String[] args = new String[7 + len];
1634        args[0] = "--runasdn";
1635        args[1] = bindDN;
1636        args[2] = "-w";
1637        args[3] = bindPasswd;
1638        args[4] = "-c";
1639        args[5] = "-v";
1640        args[6] = "-s";
1641        for (int i = 0; i < len; i++) {
1642            args[7 + i] = fileList.get(i);
1643        }
1644        invokeAdminCLI(args);
1645    }
1646
1647    // getAttributeValue - retrieve attribute value
1648    public void getAttributeValue(String fileName) throws UpgradeException {
1649        String[] args = new String[8];
1650        args[0] = "--runasdn";
1651        args[1] = bindDN;
1652        args[2] = "-w";
1653        args[3] = bindPasswd;
1654        args[4] = "-c";
1655        args[5] = "-v";
1656        args[6] = "-t";
1657        args[7] = fileName;
1658        invokeAdminCLI(args);
1659    }
1660
1661    /**
1662     * Returns the absolute path of new service schema xml file.
1663     *
1664     * @param fileName name of the service xml.
1665     * @return the absolute path of the file.
1666     */
1667    public static String getNewServiceNamePath(String fileName) {
1668        StringBuilder sb = new StringBuilder();
1669        sb.append(basedir).append(File.separator).append("upgrade").
1670                append(File.separator).
1671                append("xml").append(File.separator).
1672                append(fileName);
1673        return sb.toString();
1674    }
1675
1676    /**
1677     * Returns the absolute path of the <code>serverdefaults</code>
1678     * properties file. This file is located in the staging directory
1679     * under WEB-INF/classes.
1680     *
1681     * @return the absolute path of the file.
1682     */
1683    public static String getServerDefaultsPath() {
1684
1685        StringBuilder sb = new StringBuilder();
1686        sb.append(stagingDir).append(File.separator).
1687                append("WEB-INF").append(File.separator).
1688                append("classes").append(File.separator).
1689                append(File.separator).append(SERVER_DEFAULTS_FILE);
1690
1691        return sb.toString();
1692    }
1693
1694    /**
1695     * Returns the absolute path of the sms template files.
1696     * properties file. This file is located in the staging directory
1697     * under WEB-INF/template/sms.
1698     *
1699     * @return the absolute path of the file.
1700     */
1701    public static String getServiceTemplateDir(String SCHEMA_FILE) {
1702
1703        StringBuilder sb = new StringBuilder();
1704        sb.append(stagingDir).append(File.separator).
1705                append("WEB-INF").append(File.separator).
1706                append("template").append(File.separator).
1707                append("sms").append(File.separator).
1708                append(SCHEMA_FILE);
1709
1710        return sb.toString();
1711    }
1712
1713    /**
1714     * Returns the absolute path of service schema xml file.
1715     * The new service schema file will be located in the
1716     * staging directory under WEB-INF/classes.
1717     *
1718     * @param serviceName name of the service.
1719     * @param fileName name of the file.
1720     * @return the absolute path of the file.
1721     */
1722    public static String getAbsolutePath(String serviceName, String fileName) {
1723        StringBuilder sb = new StringBuilder();
1724        sb.append(basedir).append(File.separator).append("upgrade")
1725                .append(File.separator).append("services")
1726                .append(File.separator).append(serviceName)
1727                .append(File.separator).append("data")
1728                .append(File.separator).append(fileName);
1729
1730        return sb.toString();
1731    }
1732
1733    /**
1734     * Returns the name of a service
1735     *
1736     * @param doc The service definition file in XML
1737     * @return The name of the service
1738     */
1739    public static String getServiceName(Document doc) {
1740        NodeList nodes = doc.getElementsByTagName(SMSUtils.SERVICE);
1741        Node serviceNode = nodes.item(0);
1742
1743        return XMLUtils.getNodeAttributeValue(serviceNode, SMSUtils.NAME);
1744    }
1745
1746    /**
1747     * Returns the ssoToken used for admin operations.
1748     * NOTE: this might be replaced later.
1749     *
1750     * @param bindUser the user distinguished name.
1751     * @param bindPwd the user password
1752     * @return the <code>SSOToken</code>
1753     */
1754    private static SSOToken ldapLoginInternal(
1755            String bindUser,
1756            String bindPwd) {
1757
1758        String classMethod = "UpgradeUtils:ldapLoginInternal : ";
1759        SSOToken ssoToken = null;
1760        try {
1761            com.sun.identity.authentication.internal.AuthContext ac =
1762                    getLDAPAuthContext(bindUser, bindPwd);
1763            if (ac.getLoginStatus() == AUTH_SUCCESS) {
1764                ssoToken = ac.getSSOToken();
1765            } else {
1766                ssoToken = null;
1767            }
1768        } catch (LoginException le) {
1769            debug.error(classMethod + "Error creating SSOToken", le);
1770
1771        } catch (InvalidAuthContextException iace) {
1772            ssoToken = null;
1773            debug.error(classMethod + "Error creating SSOToken", iace);
1774        }
1775        return ssoToken;
1776    }
1777
1778    /**
1779     * Returns the <code>AuthContext</code>.
1780     *
1781     * @param bindUser the user distinguished name.
1782     * @param bindPwd the user password.
1783     * @return <code>AuthContext</code> object
1784     * @throws javax.security.auth.login.LoginException on error.
1785     */
1786    private static com.sun.identity.authentication.internal.AuthContext
1787            getLDAPAuthContext(String bindUser, String bindPwd)
1788            throws LoginException {
1789        com.sun.identity.authentication.internal.AuthPrincipal principal =
1790                new com.sun.identity.authentication.internal.AuthPrincipal(
1791                bindUser);
1792        com.sun.identity.authentication.internal.AuthContext authContext =
1793                new com.sun.identity.authentication.internal.AuthContext(
1794                principal, bindPwd.toCharArray());
1795        return authContext;
1796    }
1797
1798    // legacy code to invoke amadmin cli
1799    static void invokeAdminCLI(String[] args) throws UpgradeException {
1800        /*
1801         * Set the property to inform AdminTokenAction that
1802         * "amadmin" CLI is executing the program
1803         */
1804        SystemProperties.initializeProperties(
1805                AdminTokenAction.AMADMIN_MODE, "true");
1806
1807        // Initialize Crypt class
1808        Crypt.checkCaller();
1809
1810        /*Main dpa = new Main();
1811        try {
1812            dpa.parseCommandLine(args);
1813            dpa.runCommand();
1814        } catch (Exception eex) {
1815            throw new UpgradeException(eex.getMessage());
1816        }*/
1817    }
1818
1819    // return the properties
1820    public static Properties getProperties(String file) {
1821
1822        String classMethod = "UpgradeUtils:getProperties : ";
1823        Properties properties = new Properties();
1824        try {
1825            properties.load(new FileInputStream(file));
1826        } catch (FileNotFoundException fe) {
1827            debug.error(classMethod + "File Not found" + file, fe);
1828        } catch (IOException ie) {
1829            debug.error(classMethod + "Error reading file" + file, ie);
1830        }
1831        propertyFileMap.put(file,properties);
1832        return properties;
1833    }
1834
1835    /**
1836     * Checks the service scheam for existance of an attribute.
1837     *
1838     * @param serviceName name of the service.
1839     * @param attributeName the attribute name
1840     * @param schemaType the schema type
1841     * @return true if attrbute exist else false.
1842     * @throws UpgradeException if there is an error
1843     */
1844    public static boolean attributeExists(
1845            String serviceName,
1846            String attributeName,
1847            String schemaType)
1848            throws UpgradeException {
1849        boolean isExists = false;
1850        try {
1851            ServiceSchemaManager sm = getServiceSchemaManager(serviceName);
1852            ServiceSchema ss = sm.getSchema(schemaType);
1853            Map attributeDefaults = ss.getAttributeDefaults();
1854            if (attributeDefaults.containsKey(attributeName)) {
1855                HashSet hashSet =
1856                        (HashSet) attributeDefaults.get(attributeName);
1857                String value = (String) (hashSet.iterator().next());
1858                isExists = true;
1859            }
1860        } catch (SMSException sme) {
1861            throw new UpgradeException("Error getting attribute value");
1862        }
1863        return isExists;
1864    }
1865
1866    /**
1867     * Returns a value of an attribute.
1868     * This method assumes that the attribute is single valued.
1869     *
1870     * @param serviceName name of the service.
1871     * @param attributeName name of the attribute.
1872     * @param schemaType the schema type.
1873     * @return the value of the attribute
1874     * @throws UpgradeException if there is an error.
1875     */
1876    public static String getAttributeValueString(
1877            String serviceName,
1878            String attributeName,
1879            String schemaType) throws UpgradeException {
1880        String value = null;
1881        try {
1882            ServiceSchemaManager sm = getServiceSchemaManager(serviceName);
1883            ServiceSchema ss = sm.getSchema(schemaType);
1884            Map attributeDefaults = ss.getAttributeDefaults();
1885            if (attributeDefaults.containsKey(attributeName)) {
1886                HashSet hashSet =
1887                        (HashSet) attributeDefaults.get(attributeName);
1888                value = (String) (hashSet.iterator().next());
1889            }
1890        } catch (SMSException sme) {
1891            throw new UpgradeException("Error getting attr value : "
1892                    + sme.getMessage());
1893        }
1894        return value;
1895    }
1896
1897    /**
1898     * Returns a set of values of an attribute.
1899     *
1900     * @param serviceName name of the service.
1901     * @param attributeName the attribute name.
1902     * @param schemaType the schema type.
1903     * @return a set of values for the attribute.
1904     * @throws UpgradeException if there is an error.
1905     */
1906    public static Set getAttributeValue(String serviceName,
1907            String attributeName,
1908            String schemaType) throws UpgradeException {
1909        return getAttributeValue(serviceName, attributeName, schemaType, false);
1910    }
1911
1912    /**
1913     * Returns a set of values of an attribute.
1914     *
1915     * @param serviceName name of the service.
1916     * @param attributeName the attribute name.
1917     * @param schemaType the schema type.
1918     * @param isOrgAttrSchema boolean value indicating whether
1919     *        the attribute is to be retrieved from
1920     *        &lt;OrganizationAttributeSchema&gt;
1921     * @return a set of values for the attribute.
1922     * @throws UpgradeException if there is an error.
1923     */
1924    public static Set getAttributeValue(String serviceName,
1925            String attributeName, String schemaType, boolean isOrgAttrSchema)
1926            throws UpgradeException {
1927        String classMethod = "UpgradeUtils:getAttributeValue : ";
1928        Set attrValues = Collections.EMPTY_SET;
1929        try {
1930            ServiceSchemaManager sm = getServiceSchemaManager(serviceName);
1931            ServiceSchema ss = null;
1932            if (isOrgAttrSchema) {
1933                ss = sm.getOrganizationCreationSchema();
1934            } else {
1935                ss = sm.getSchema(schemaType);
1936            }
1937            Map attributeDefaults = ss.getAttributeDefaults();
1938            if (attributeDefaults.containsKey(attributeName)) {
1939                attrValues = (Set) attributeDefaults.get(attributeName);
1940            }
1941        } catch (SMSException sme) {
1942            debug.error(classMethod +
1943                    "Error retreiving attribute values : ",sme);
1944            throw new UpgradeException("Unable to get attribute values : "
1945                    + sme.getMessage());
1946        }
1947        return attrValues;
1948    }
1949
1950    /**
1951     * Creates a site configuration.
1952     *
1953     * @param siteURL the site URL.
1954     * @param accessPoints a set of access points for the site.
1955     * @throws UpgradeException if there is an error.
1956     */
1957    public static void createSite(String siteURL,
1958            Set accessPoints) throws UpgradeException {
1959        try {
1960            SiteConfiguration.createSite(ssoToken, siteURL,
1961                    siteURL, accessPoints);
1962        } catch (ConfigurationException ce) {
1963            throw new UpgradeException("Unable to create Service instance");
1964        } catch (SMSException sme) {
1965            throw new UpgradeException("Unable to add to site");
1966        } catch (SSOException ssoe) {
1967            throw new UpgradeException("invalid ssotoken");
1968        }
1969    }
1970
1971    /**
1972     * Returns the server instance name.
1973     * The server instance is the server name appended with the
1974     * deployURI.
1975     *
1976     * @param serverName name of the server
1977     * @return the server instance name.
1978     */
1979    public static String getServerInstance(String serverName) {
1980        if (serverName == null) {
1981            serverName = getServerName();
1982        }
1983        String deployURI = (String) configTags.get("DEPLOY_URI");
1984        if (serverName !=null && !serverName.endsWith(deployURI)){
1985            return serverName + "/" + deployURI;
1986        } else {
1987            return serverName;
1988        }
1989    }
1990
1991    /**
1992     * Creates a service instance.
1993     *
1994     * @param serverInstance the server instance value
1995     * @param serverId the server identifier
1996     * @throws UpgradeException if there is an error.
1997     */
1998    public static void createServiceInstance(
1999            String serverInstance, String serverId) {
2000        String classMethod = "UpgradeUtils:createServiceInstance : ";
2001        if (debug.messageEnabled()) {
2002            debug.message(classMethod +  "serverInstance :" + serverInstance);
2003            debug.message(classMethod + "serverId :" + serverId);
2004        }
2005        try {
2006            ServerConfiguration.createServerInstance(
2007                    ssoToken, serverInstance,
2008                    serverId, Collections.EMPTY_SET, "");
2009        } catch (Exception e) {
2010            debug.error(classMethod + " Error creating service instance ", e);
2011        }
2012    }
2013
2014    /**
2015     * Creates a service instance.
2016     *
2017     * @param serverInstance the server instance value
2018     * @param serverId the server identifier
2019     * @throws UpgradeException if there is an error.
2020     */
2021    public static void createServiceInstance(
2022            String serverInstance, String serverId,
2023            Set values,String serverConfigXML) {
2024            //throws UpgradeException {
2025        String classMethod = "UpgradeUtils:createServiceInstance : ";
2026        if (debug.messageEnabled()) {
2027            debug.message(classMethod + "serverInstance :" + serverInstance);
2028            debug.message(classMethod + "serverId :" + serverId);
2029        }
2030        try {
2031            ServerConfiguration.createServerInstance(
2032                    ssoToken, serverInstance,
2033                    serverId, values,serverConfigXML);
2034        } catch (UnknownPropertyNameException uce) {
2035            //throw new UpgradeException("Unknwon property ");
2036        } catch (ConfigurationException ce) {
2037            //throw new UpgradeException("Unable to create Service instance");
2038        } catch (SMSException sme) {
2039            //throw new UpgradeException("Unable to create Service instance");
2040        } catch (SSOException ssoe) {
2041            //throw new UpgradeException("invalid ssotoken");
2042        }
2043    }
2044    /**
2045     * Adds server to a site.
2046     *
2047     * @param serverInstance Name of the server instance.
2048     * @param siteId Identifier of the site.
2049     * @throws UpgradeException if there is an error.
2050     */
2051    public static void addToSite(
2052            String serverInstance,
2053            String siteId) throws UpgradeException {
2054        try {
2055            ServerConfiguration.addToSite(ssoToken, serverInstance, siteId);
2056        } catch (ConfigurationException ce) {
2057            throw new UpgradeException("Unable to add to site");
2058        } catch (SMSException sme) {
2059            throw new UpgradeException("Unable to add to site");
2060        } catch (SSOException ssoe) {
2061            throw new UpgradeException("Unable to add to site");
2062        }
2063    }
2064
2065    /**
2066     * Adds attributes to service sub configuration.
2067     *
2068     * @param serviceName the service name
2069     * @param subConfigName the sub configuration name
2070     * @param attrValues Map of attributes key is the attribute name and
2071     *        value a set of attribute values.
2072     * @throws UpgradeException on error.
2073     */
2074    public static void addAttributeToSubConfiguration(
2075            String serviceName,
2076            String subConfigName,
2077            Map attrValues) throws UpgradeException {
2078        String classMethod = "UpgradeUtils:addAttributeToSubConfiguration : " ;
2079        try {
2080            ServiceConfigManager scm = getServiceConfigManager(serviceName);
2081            ServiceConfig sc = scm.getGlobalConfig(null);
2082
2083            StringTokenizer st = new StringTokenizer(subConfigName, "/");
2084            int tokenCount = st.countTokens();
2085
2086            for (int i = 1; i <= tokenCount; i++) {
2087                String scn = st.nextToken();
2088                sc = sc.getSubConfig(scn);
2089            }
2090
2091            for (Iterator i = attrValues.keySet().iterator(); i.hasNext();) {
2092                String attrName = (String) i.next();
2093                sc.addAttribute(attrName, (Set) attrValues.get(attrName));
2094            }
2095        } catch (SMSException sme) {
2096            throw new UpgradeException("Unable to add attribute to subconfig");
2097        } catch (SSOException ssoe) {
2098            throw new UpgradeException("invalid SSOToken");
2099        } catch (Exception e) {
2100            debug.error(classMethod + "Error adding attribute to subconfig:",e);
2101        }
2102        if (debug.messageEnabled()) {
2103            debug.message(classMethod + "Added attributes " + attrValues +
2104                    " to subconfig " + subConfigName
2105                    + " in service " + serviceName);
2106        }
2107    }
2108
2109    // the following methods might change.
2110    /**
2111     * Sets the distinguished name of the admin user.
2112     *
2113     * @param dn the dn of the admin user.
2114     */
2115    public static void setBindDN(String dn) {
2116        bindDN = dn;
2117    }
2118
2119    /**
2120     * Sets the deploy uri of OpenAM instance.
2121     *
2122     * @param uri the deployment uri
2123     */
2124    public static void setDeployURI(String uri) {
2125        deployURI = uri;
2126    }
2127
2128    /**
2129     * Gets the deploy uri of OpenAM instance.
2130     */
2131    public static String getDeployURI() {
2132        if (deployURI == null) {
2133            deployURI = (String) configTags.get("DEPLOY_URI");
2134        }
2135        return (deployURI);
2136    }
2137
2138    /**
2139     * Sets the password of the admin user.
2140     *
2141     * @param password the password the admin user.
2142     */
2143    public static void setBindPass(String password) {
2144        bindPasswd = password;
2145    }
2146
2147    /**
2148     * Sets the Directory Server host name.
2149     *
2150     * @param dsHost the directory server host name.
2151     */
2152    public static void setDSHost(String dsHost) {
2153        dsHostName = dsHost;
2154    }
2155
2156    /**
2157     * Sets the directory server port.
2158     *
2159     * @param port the directory server port number.
2160     */
2161    public static void setDSPort(int port) {
2162        dsPort = port;
2163    }
2164
2165    /**
2166     * Sets the distinguished name of the directory server manager.
2167     *
2168     * @param dn the dn of the directory server manager.
2169     */
2170    public static void setDirMgrDN(String dn) {
2171        dsManager = dn;
2172    }
2173
2174    /**
2175     * Sets the password of the directory server manager user.
2176     *
2177     * @param pass the password the directory server manager.
2178     */
2179    public static void setdirPass(String pass) {
2180        dsAdminPwd = pass;
2181    }
2182
2183    /**
2184     * Sets the location of the upgrade base directory.
2185     *
2186     * @param dir the name of the upgrade base directory.
2187     */
2188    public static void setBaseDir(String dir) {
2189        basedir = dir;
2190    }
2191
2192    /**
2193     * Sets the location of the staging directory.
2194     *
2195     * @param dir the name of the staging directory.
2196     */
2197    public static void setStagingDir(String dir) {
2198        stagingDir = dir;
2199    }
2200
2201    /**
2202     * Sets the configuration directory location
2203     *
2204     * @param dir the location of the config directory
2205     */
2206    public static void setConfigDir(String dir) {
2207        configDir = dir;
2208    }
2209
2210    /**
2211     * Gets the configuration directory location
2212     */
2213    public static String getConfigDir() {
2214        return configDir;
2215    }
2216
2217    /**
2218     * Returns the <code>ServiceSchemaManager</code> for a service.
2219     *
2220     * @param serviceName the service name
2221     * @return the <code>ServiceSchemaManager</code> of the service.
2222     */
2223    public static ServiceSchemaManager getServiceSchemaManager(
2224            String serviceName) {
2225        return getServiceSchemaManager(serviceName, ssoToken);
2226    }
2227
2228    /**
2229     * Returns the <code>ServiceSchemaManager</code> for a service.
2230     *
2231     * @param serviceName the service name
2232     * @param ssoToken the admin SSOToken.
2233     * @return the <code>ServiceSchemaManager</code> of the service.
2234     */
2235    protected static ServiceSchemaManager getServiceSchemaManager(
2236            String serviceName,
2237            SSOToken ssoToken) {
2238        String classMethod = "UpgradeUtils:getServiceSchemaManager : ";
2239        ServiceSchemaManager mgr = null;
2240        if (serviceName != null) {
2241            try {
2242                if (serviceName.equals(IDFF_PROVIDER_SERVICE)) {
2243                    mgr = new ServiceSchemaManager(ssoToken,
2244                         serviceName,IDFF_SERVICE_VERSION);
2245                } else {
2246                    mgr = new ServiceSchemaManager(serviceName, ssoToken);
2247                }
2248            } catch (SSOException e) {
2249                debug.error(classMethod +
2250                        "SchemaCommand.getServiceSchemaManager", e);
2251            } catch (SMSException e) {
2252                debug.error(classMethod +
2253                        "SchemaCommand.getServiceSchemaManager", e);
2254            } catch (Exception e) {
2255                debug.error(classMethod + "Error : ", e);
2256            }
2257        }
2258        return mgr;
2259    }
2260
2261    static ServiceSchema getServiceSchema(String serviceName,
2262            String subSchemaName, String schemaType)
2263    throws UpgradeException {
2264        return getServiceSchema(serviceName, subSchemaName, schemaType, null);
2265    }
2266
2267    /**
2268     * Returns the <code>ServiceSchema</code> of a service.
2269     *
2270     * @param serviceName the service name
2271     * @param subSchemaName the sub schema.
2272     * @param schemaType the schema type.
2273     * @return the <code>ServiceSchema</code> object.
2274     * @throws UpgradeException if there is an error.
2275     */
2276    static ServiceSchema getServiceSchema(String serviceName,
2277            String subSchemaName, String schemaType, SSOToken adminToken)
2278            throws UpgradeException {
2279        ServiceSchema ss = null;
2280        try {
2281            SchemaType sType = getSchemaType(schemaType);
2282            ServiceSchemaManager ssm = getServiceSchemaManager(serviceName, adminToken);
2283            ss = ssm.getSchema(sType);
2284            if (subSchemaName != null) {
2285                ss = ss.getSubSchema(subSchemaName);
2286            }
2287        } catch (SMSException sme) {
2288            throw new UpgradeException("Cannot get service schema : "
2289                    + sme.getMessage());
2290        }
2291        return ss;
2292    }
2293
2294    /**
2295     * Returns the <code>SchemaType</code>
2296     *
2297     * @param schemaTypeName the schema type string value
2298     * @return the <code>SchemaType</code> object.
2299     */
2300    private static SchemaType getSchemaType(String schemaTypeName) {
2301        SchemaType schemaType = null;
2302        if (schemaTypeName.equalsIgnoreCase(SCHEMA_TYPE_GLOBAL)) {
2303            schemaType = SchemaType.GLOBAL;
2304        } else if (schemaTypeName.equalsIgnoreCase(SCHEMA_TYPE_ORGANIZATION)) {
2305            schemaType = SchemaType.ORGANIZATION;
2306        } else if (schemaTypeName.equalsIgnoreCase(SCHEMA_TYPE_DYNAMIC)) {
2307            schemaType = SchemaType.DYNAMIC;
2308        } else if (schemaTypeName.equalsIgnoreCase(SCHEMA_TYPE_USER)) {
2309            schemaType = SchemaType.USER;
2310        } else if (schemaTypeName.equalsIgnoreCase(SCHEMA_TYPE_POLICY)) {
2311            schemaType = SchemaType.POLICY;
2312        }
2313        return schemaType;
2314    }
2315
2316    /**
2317     * Returns the <code>ServiceManager</code>.
2318     *
2319     * @return the <code>ServiceManager</code> object.
2320     * @throws <code>UpgradeException</cpde> if there is an error.
2321     */
2322    private static ServiceManager getServiceManager() throws UpgradeException {
2323        ServiceManager ssm = null;
2324
2325        if (ssoToken == null) {
2326            getSSOToken();
2327        }
2328
2329        try {
2330            ssm = new ServiceManager(ssoToken);
2331        } catch (SMSException e) {
2332            throw new UpgradeException("Error creating Service manager");
2333        } catch (SSOException e) {
2334            throw new UpgradeException("Invalid SSOToken");
2335        }
2336        return ssm;
2337    }
2338
2339    /**
2340     * Returns the <code>ServiceManager</code>.
2341     *
2342     * @param adminToken admin SSOToken
2343     * @return the <code>ServiceManager</code> object.
2344     * @throws <code>UpgradeException</cpde> if there is an error.
2345     */
2346    private static ServiceManager getServiceManager(SSOToken adminToken)
2347    throws UpgradeException {
2348        ServiceManager ssm = null;
2349
2350        try {
2351            ssm = new ServiceManager(adminToken);
2352        } catch (SMSException e) {
2353            throw new UpgradeException("Error creating Service manager");
2354        } catch (SSOException e) {
2355            throw new UpgradeException("Invalid SSOToken");
2356        }
2357
2358        return ssm;
2359    }
2360
2361    /**
2362     * Adds module names to the list of authenticators in core auth
2363     * service.
2364     *
2365     * @param moduleName a set of authentication module names.
2366     * @throws UpgradeException if there is an error.
2367     */
2368    public static void updateAuthenticatorsList(Set moduleName)
2369            throws UpgradeException {
2370        addAttributeDefaultValues(AUTH_SERVICE_NAME, null, SCHEMA_TYPE_GLOBAL,
2371                AUTH_ATTR_NAME, moduleName);
2372    }
2373
2374    /**
2375     * Returns the <code>ServiceConfigManager</code> for a service.
2376     *
2377     * @param serviceName the service name
2378     * @return the <code>ServiceConfigManager</code> of the service.
2379     */
2380    protected static ServiceConfigManager getServiceConfigManager(
2381            String serviceName) {
2382        return getServiceConfigManager(serviceName, ssoToken);
2383    }
2384
2385    /**
2386     * Returns the <code>ServiceConfigManager</code> for a service.
2387     *
2388     * @param serviceName the service name
2389     * @param ssoToken the admin SSOToken.
2390     * @return the <code>ServiceConfigManager</code> of the service.
2391     */
2392    protected static ServiceConfigManager getServiceConfigManager(
2393            String serviceName,
2394            SSOToken ssoToken) {
2395        String classMethod = "UpgradeUtils:getServiceConfigManager : ";
2396        ServiceConfigManager scm = null;
2397        if (serviceName != null) {
2398            try {
2399                scm = new ServiceConfigManager(serviceName, ssoToken);
2400            } catch (SSOException e) {
2401                debug.error(classMethod, e);
2402            } catch (SMSException e) {
2403                debug.error(classMethod, e);
2404            }
2405        }
2406        return scm;
2407    }
2408
2409    /**
2410     * Modifies the i18nKey of the specified attribute in the schema.
2411     *
2412     * @param serviceName the service name where the attribute exists.
2413     * @param subSchema the subschema name.
2414     * @param schemaType the schema type
2415     * @param attrName the attribute name.
2416     * @param value the value of the i18nKey
2417     * @throws UpgradeException if there is an error.
2418     */
2419    public static void modifyI18NInAttributeSchema(
2420            String serviceName,
2421            String subSchema,
2422            String schemaType,
2423            String attrName,
2424            String value) throws UpgradeException
2425    {
2426        try {
2427            ServiceSchema ss =
2428                getServiceSchema(serviceName, subSchema, schemaType);
2429            AttributeSchema attrSchema = ss.getAttributeSchema(attrName);
2430            attrSchema.setI18NKey(value);
2431        } catch (SSOException ssoe) {
2432            throw new UpgradeException("Invalid token");
2433        } catch (SMSException sme) {
2434            throw new UpgradeException("Error setting i18N attribute");
2435        }
2436   }
2437
2438    /**
2439     * Creates auth configurations for auth modules configuration in
2440     * core auth service.
2441     */
2442    private static void createOrgAuthConfig(String realmName) throws Exception {
2443
2444        String classMethod = "UpgradeUtils:createOrgAuthConfig: ";
2445        OrganizationConfigManager org =
2446                new OrganizationConfigManager(ssoToken, realmName);
2447        ServiceConfig orgConfig = org.getServiceConfig(AUTH_SERVICE_NAME);
2448        if (orgConfig != null) {
2449            Map aa = orgConfig.getAttributes();
2450            if (debug.messageEnabled()) {
2451                debug.message(classMethod + "Org is :" + realmName);
2452                debug.message(classMethod + "Attribute Map is :" + aa);
2453            }
2454            String orgName = realmName;
2455            if (DN.isDN(realmName)) {
2456                orgName = LDAPDN.explodeDN(realmName, true)[0];
2457            }
2458            String authConfigName = orgName + "-authconfig";
2459            String adminAuthConfigName = orgName + "-admin-authconfig";
2460            Set authConfigAttrValue =
2461                    (Set) aa.get(ATTR_ORG_AUTH_MODULE);
2462            if (debug.messageEnabled()) {
2463                debug.message(classMethod + "authConfigAttrValue : "
2464                        + authConfigAttrValue);
2465            }
2466            Set newVal = new HashSet();
2467            if (authConfigAttrValue.size() != 1 &&
2468                    !authConfigAttrValue.contains(authConfigName)) {
2469                newVal.add(authConfigName);
2470                orgConfig.replaceAttributeValues(
2471                        ATTR_ORG_AUTH_MODULE, authConfigAttrValue, newVal);
2472            }
2473            Set adminConfigAttrValue = (Set) aa.get(ATTR_ADMIN_AUTH_MODULE);
2474            if (debug.messageEnabled()) {
2475                debug.message("adminauthConfigAttrValue : "
2476                        + adminConfigAttrValue);
2477            }
2478            if (adminConfigAttrValue.size() != 1 &&
2479                    !adminConfigAttrValue.contains(adminAuthConfigName)) {
2480                newVal.clear();
2481                newVal.add(adminAuthConfigName);
2482                orgConfig.replaceAttributeValues(ATTR_ADMIN_AUTH_MODULE,
2483                        adminConfigAttrValue, newVal);
2484            }
2485            aa = orgConfig.getAttributes();
2486            ServiceConfig s = org.getServiceConfig(AUTH_CONFIG_SERVICE);
2487            ServiceConfig authConfig = s.getSubConfig(NAMED_CONFIG);
2488            if (authConfig == null) {
2489                s.addSubConfig(NAMED_CONFIG, null, 0, null);
2490                authConfig = s.getSubConfig(NAMED_CONFIG);
2491            }
2492            Map aMap = new HashMap();
2493            aMap.put(ATTR_AUTH_CONFIG, authConfigAttrValue);
2494            authConfig.addSubConfig(authConfigName, SUB_NAMED_CONFIG, 0, aMap);
2495            aMap.clear();
2496            aMap.put(ATTR_AUTH_CONFIG, adminConfigAttrValue);
2497            authConfig.addSubConfig(adminAuthConfigName,
2498                    SUB_NAMED_CONFIG, 0, aMap);
2499        }
2500    }
2501
2502    /**
2503     * Returns value of an attribute.
2504     * @param attrName name of the attribute.
2505     * @param attrs Map of attributes where key is the attribute name
2506     *        and values are a set of attributes.
2507     * @return the value of attribute if it is found else null.
2508     */
2509    public static String getAttributeString(String attrName, Map attrs) {
2510        return getAttributeString(attrName, attrs, null);
2511    }
2512
2513    /**
2514     * Returns value of an attribute.
2515     *
2516     * @param attrName name of the attribute.
2517     * @param attrs Map of attributes where key is the attribute name
2518     *          and values are a set of attributes.
2519     * @param defaultValue the default value to be returned if value
2520     *          is not found.
2521     * @return the value of attribute if it is found else returns
2522     *          the defaultValue.
2523     */
2524    public static String getAttributeString(String attrName, Map attrs,
2525            String defaultValue) {
2526        String attrValue = defaultValue;
2527        Set attrValSet = (Set) attrs.get(attrName);
2528        if (attrValSet != null && !attrValSet.isEmpty()) {
2529            attrValue = (String) (attrValSet.toArray())[0];
2530        }
2531        return attrValue;
2532    }
2533
2534    /**
2535     * Creates Realm Admin Policy.
2536     *
2537     * @param policyManager the policy manager object.
2538     * @param orgDN the organization dn.
2539     * @param orgID the organization identifier.
2540     */
2541    private static void createRealmAdminPolicy(PolicyManager policyManager,
2542            String orgDN, String orgID) {
2543        String classMethod = "UpgradeUtils:createRealmAdminPolicy";
2544        try {
2545            String policyName = orgID + "^^RealmAdmin";
2546            Policy realmPolicy = new Policy(policyName, null, false, true);
2547            // create Rule
2548            String resourceName = "sms://*" + orgDN + "/*";
2549
2550            Rule rule = getRule(DELEGATION_SERVICE, resourceName);
2551
2552            if (rule != null) {
2553                realmPolicy.addRule(rule);
2554            }
2555
2556            String universalID = getUniversalID(orgDN, ORG_ADMIN_ROLE);
2557            Subject subject = getSubject(policyManager, universalID);
2558            if (subject != null) {
2559                realmPolicy.addSubject(DELEGATION_SUBJECT, subject, false);
2560            }
2561            policyManager.addPolicy(realmPolicy);
2562        } catch (Exception e) {
2563            debug.error(classMethod + "Error creating realm admin policy", e);
2564        }
2565    }
2566
2567    /**
2568     * Creates Policy Admin Policy.
2569     *
2570     * @param policyManager the policy manager object.
2571     * @param orgDN the organization dn.
2572     * @param orgID the organization identifier.
2573     */
2574    private static void createPolicyAdminPolicy(PolicyManager policyManager,
2575            String orgDN, String orgID) {
2576        String classMethod = "UpgradeUtils:createRealmReadOnlyPolicy";
2577        try {
2578            String policyName = orgID + "^^PolicyAdmin";
2579            Policy realmPolicy = new Policy(policyName, null, false, true);
2580            // create Rule
2581            String resourceName = "sms://*" + orgDN + "/" + POLICY_SERVICE;
2582            Rule rule = getRule(DELEGATION_SERVICE, resourceName);
2583            if (rule != null) {
2584                realmPolicy.addRule(rule);
2585            }
2586            // add subjects
2587            String policyAdminRoleUniversalID =
2588                    getUniversalID(orgDN, ORG_POLICY_ADMIN_ROLE);
2589            Subject subject =
2590                    getSubject(policyManager, policyAdminRoleUniversalID);
2591            if (subject != null) {
2592                realmPolicy.addSubject(DELEGATION_SUBJECT, subject, false);
2593            }
2594            policyManager.addPolicy(realmPolicy);
2595        } catch (Exception e) {
2596            debug.error(classMethod + "Error creating policy admin policy", e);
2597        }
2598    }
2599
2600    /**
2601     * Creates Realm Read Only Policy
2602     *
2603     * @param policyManager the policy manager object.
2604     * @param orgDN the organization dn.
2605     * @param orgID the organization identifier.
2606     */
2607    private static void createRealmReadOnlyPolicy(PolicyManager policyManager,
2608            String orgDN, String orgID) {
2609        String classMethod = "UpgradeUtils:createRealmReadOnlyPolicy";
2610        try {
2611            String policyName = orgID + "^^" + REALM_READ_ONLY;
2612            Policy realmPolicy = new Policy(policyName, null, false, true);
2613            // create Rule
2614            String serviceName = DELEGATION_SERVICE;
2615            String resourceName = "sms://*" + orgDN + "/" + REALM_SERVICE;
2616            Rule rule = getRule(serviceName, resourceName);
2617            if (rule != null) {
2618                realmPolicy.addRule(rule);
2619            }
2620            // add subjects
2621            String policyAdminRoleUniversalID =
2622                    getUniversalID(orgDN, ORG_POLICY_ADMIN_ROLE);
2623            Subject subject =
2624                    getSubject(policyManager, policyAdminRoleUniversalID);
2625            if (subject != null) {
2626                realmPolicy.addSubject(DELEGATION_SUBJECT, subject, false);
2627            }
2628            policyManager.addPolicy(realmPolicy);
2629        } catch (Exception e) {
2630            debug.error(classMethod +
2631                    "Error creating realm read only policy", e);
2632        }
2633    }
2634
2635    /**
2636     * Creates DataStores Read Only Policy
2637     *
2638     * @param policyManager the policy manager object.
2639     * @param orgDN the organization dn.
2640     * @param orgID the organization identifier.
2641     */
2642    private static void createDatastoresReadOnlyPolicy(
2643            PolicyManager policyManager, String orgDN, String orgID) {
2644        String classMethod = "UpgradeUtils:createDatastoresReadOnlyPolicy";
2645        try {
2646            String policyName = orgID + "^^" + DATA_STORE_READ_ONLY;
2647            Policy realmPolicy = new Policy(policyName, null, false, true);
2648            // create Rule
2649            String serviceName = DELEGATION_SERVICE;
2650            String resourceName = "sms://*" + orgDN + "/" + IDREPO_SERVICE;
2651            Rule rule = getRule(serviceName, resourceName);
2652            if (rule != null) {
2653                realmPolicy.addRule(rule);
2654            }
2655            // add subjects
2656            String policyAdminRoleUniversalID =
2657                    getUniversalID(orgDN, ORG_POLICY_ADMIN_ROLE);
2658            Subject subject =
2659                    getSubject(policyManager, policyAdminRoleUniversalID);
2660            if (subject != null) {
2661                realmPolicy.addSubject(DELEGATION_SUBJECT, subject, false);
2662            }
2663            policyManager.addPolicy(realmPolicy);
2664        } catch (Exception e) {
2665            debug.error(classMethod +
2666                    "Error creating datastores readonly policy", e);
2667        }
2668    }
2669
2670    /**
2671     * Returns the policy <code>Rule</code> object.
2672     *
2673     * @param serviceName name of the service.
2674     * @param resourceName name of the resource
2675     * @return <code>Rule</code> object.
2676     */
2677    private static Rule getRule(String serviceName, String resourceName) {
2678        String classMethod = "UpgradeUtils:getRule : ";
2679        Rule rule = null;
2680        try {
2681            Map actionsMap = new HashMap();
2682            Set values = new HashSet();
2683            values.add("allow");
2684            actionsMap.put("MODIFY", values);
2685            actionsMap.put("DELEGATE", values);
2686            actionsMap.put("READ", values);
2687            rule = new Rule(serviceName, resourceName, actionsMap);
2688        } catch (Exception e) {
2689            debug.error(classMethod + "Error creating rule ", e);
2690        }
2691        return rule;
2692    }
2693
2694    /**
2695     * Returns the policy <code>Rule</code> object.
2696     *
2697     * @param serviceName name of the service.
2698     * @param resourceName name of the resource
2699     * @param actionsMap map of allowed actions on the resource.
2700     *        the key is the actions (MODIFY,DELEGATE,READ)
2701     *        and the values is a set indicating whether
2702     *        action is allowed or denied.
2703     * @return <code>Rule</code> object.
2704     */
2705    private static Rule getRule(String ruleName,String serviceName,
2706        String resourceName, Map actionsMap) {
2707        String classMethod = "UpgradeUtils:getRule : ";
2708        Rule rule = null;
2709        try {
2710            rule = new Rule(ruleName,serviceName, resourceName, actionsMap);
2711        } catch (Exception e) {
2712            debug.error(classMethod + "Error creating rule ", e);
2713        }
2714        return rule;
2715    }
2716
2717    /**
2718     * Returns the policy <code>Subject</code>
2719     *
2720     */
2721    private static Subject getSubject(PolicyManager policyManager,
2722            String universalID) {
2723        String classMethod = "UpgradeUtils:getSubject : ";
2724        Subject subject = null;
2725        try {
2726            SubjectTypeManager stm = policyManager.getSubjectTypeManager();
2727            subject = stm.getSubject(AM_ID_SUBJECT);
2728            Set subjectValues = new HashSet(1);
2729            subjectValues.add(universalID);
2730            subject.setValues(subjectValues);
2731        } catch (Exception e) {
2732            debug.error(classMethod + "Error creating subject", e);
2733        }
2734        return subject;
2735    }
2736
2737    /**
2738     * Returns the universal identifier of an identity
2739     */
2740    private static String getUniversalID(String orgDN, String idName) {
2741        return new StringBuilder().append("id=").append(idName)
2742                .append(",ou=role,").append(orgDN).append(",amsdkdn=cn=")
2743                .append(idName).append(",").append(orgDN).toString();
2744    }
2745
2746    /**
2747     * Return sub configurations in a service.
2748     *
2749     * @param serviceName the service name.
2750     * @param serviceVersion the version of the service
2751     * @param realm the realm to retreive the sub configs from.
2752     * @return a set containing the org sub configurations.
2753     */
2754    static Set getOrgSubConfigs(String serviceName,
2755            String serviceVersion,String realm) {
2756        String classMethod = "UpgradeUtils:getOrgSubConfigs : ";
2757        Set subConfigs;
2758        try {
2759            ServiceConfigManager scm = new ServiceConfigManager(
2760                    ssoToken, serviceName, serviceVersion);
2761            ServiceConfig orgConfig =
2762                    scm.getOrganizationConfig(realm, null);
2763            subConfigs = orgConfig.getSubConfigNames();
2764            if (debug.messageEnabled()) {
2765                debug.message(classMethod + "Org subConfigs : " + subConfigs);
2766            }
2767        } catch (Exception e) {
2768            if (debug.messageEnabled()) {
2769                debug.message(classMethod + "No organization subconfigs" , e);
2770            }
2771            subConfigs = Collections.EMPTY_SET;
2772        }
2773        return subConfigs;
2774    }
2775
2776    /**
2777     * Replace tags in the upgrade services xmls
2778     */
2779    static void replaceTags(File dir, Properties p) {
2780        try {
2781            LinkedList fileList = new LinkedList();
2782            getFiles(dir, fileList);
2783            ListIterator srcIter = fileList.listIterator();
2784            while (srcIter.hasNext()) {
2785                File file = (File) srcIter.next();
2786                String fname = file.getAbsolutePath();
2787                if (fname.endsWith("xml") || fname.endsWith("ldif")) {
2788                    replaceTag(fname, p);
2789                }
2790            }
2791        } catch (Exception e) {
2792        // do nothing
2793        }
2794    }
2795    // replace tags
2796    static void replaceTag(String fname, Properties p) {
2797        String line;
2798        StringBuilder sb = new StringBuilder();
2799        try {
2800            FileInputStream fis = new FileInputStream(fname);
2801            BufferedReader reader =
2802                    new BufferedReader(new InputStreamReader(fis));
2803            while ((line = reader.readLine()) != null) {
2804                Enumeration e = p.propertyNames();
2805                while (e.hasMoreElements()) {
2806                    String oldPattern = (String) e.nextElement();
2807                    String newPattern = (String) p.getProperty(oldPattern);
2808                    String oldAtPattern = "@" + oldPattern + "@" ;
2809                    if (line != null && line.contains(oldAtPattern)) {
2810                         line = line.replaceAll(oldAtPattern, newPattern);
2811                    } else {
2812                         line = line.replaceAll(oldPattern, newPattern);
2813                    }
2814                }
2815                sb.append(line).append('\n');
2816            }
2817            reader.close();
2818            BufferedWriter out = new BufferedWriter(new FileWriter(fname));
2819            out.write(sb.toString());
2820            out.close();
2821        } catch (Exception e) {
2822        // do nothing
2823        }
2824    }
2825
2826    protected static void setProperties(Properties p) {
2827        configTags = p;
2828    }
2829
2830    /**
2831     * Returns a list of files in a directory.
2832     *
2833     * @param dirName the directory name
2834     * @param fileList the file list to be retrieved.
2835     */
2836    public static void getFiles(File dirName,
2837            LinkedList fileList) {
2838        File[] fromFiles = dirName.listFiles();
2839        for (int i = 0; i < fromFiles.length; i++) {
2840            fileList.addLast(fromFiles[i]);
2841            if (fromFiles[i].isDirectory()) {
2842                getFiles(fromFiles[i], fileList);
2843            }
2844        }
2845    }
2846
2847    /**
2848     * Creates the default server configuration .
2849     * The values are read from the AMConfig.properties and for each server
2850     * instance a subconfig is created under
2851     * <code>com-sun-identity-servers</code>
2852     *
2853     * @param serviceName the service name
2854     * @param subConfigName the sub configuration name.
2855     * @param instanceName the instance name
2856     * @param instanceID the instance identifier
2857     * @param values a Set of values to be set.
2858     * @param serverConfigXML string representation of
2859     *     <code>serverconfig.xml</code>
2860     * @throws UpgradeException if there is an error.
2861     */
2862    public static void addServerDefaults(String serviceName,
2863            String subConfigName, String instanceName, String instanceID,
2864            Set values,String serverConfigXML) throws UpgradeException {
2865        String classMethod = "UpgradeUtils:addServerDefaults : ";
2866        if (debug.messageEnabled()) {
2867            debug.message(classMethod + "serviceName :" + serviceName);
2868            debug.message(classMethod + "subConfigName :" + subConfigName);
2869            debug.message(classMethod + "instanceName:" + instanceName);
2870            debug.message(classMethod + "instanceID:" + instanceID);
2871            debug.message(classMethod + "values:" + values);
2872        }
2873
2874        try {
2875            ServiceConfigManager scm =
2876                    new ServiceConfigManager(serviceName, getSSOToken());
2877            ServiceConfig globalSvcConfig = scm.getGlobalConfig(null);
2878            ServiceConfig gConfig = globalSvcConfig.getSubConfig(subConfigName);
2879
2880            Map serverValues = new HashMap(4);
2881            Set setServerId = new HashSet(2);
2882            setServerId.add(instanceID);
2883            serverValues.put(ATTR_SERVER_ID, setServerId);
2884
2885            Set setServerConfigXML = new HashSet(2);
2886            String file = configDir + File.separator + SERVER_CONFIG_XML;
2887            if (serverConfigXML == null) {
2888                serverConfigXML = readFile(file);
2889            }
2890            setServerConfigXML.add(serverConfigXML);
2891            serverValues.put(ATTR_SERVER_CONFIG, values);
2892            serverValues.put(ATTR_SERVER_CONFIG_XML, setServerConfigXML);
2893            if (instanceName == null) {
2894                gConfig.addSubConfig(CONFIG_SERVER_DEFAULT,
2895                        SUB_SCHEMA_SERVER, 0, serverValues);
2896            } else {
2897                gConfig.addSubConfig(instanceName,
2898                    SUB_SCHEMA_SERVER, 0, serverValues);
2899            }
2900        } catch (Exception e) {
2901            debug.error(classMethod + "Error adding server instance :", e);
2902            throw new UpgradeException(e.getMessage());
2903        }
2904    }
2905
2906    /**
2907     * Reads a file into a string.
2908     */
2909    private static String readFile(String fileName) {
2910        String classMethod = "UpgradeUtils:readFile : ";
2911        StringBuilder fileData = new StringBuilder();
2912        String fileString = "";
2913        try {
2914             BufferedReader reader = new BufferedReader(
2915                 new FileReader(fileName));
2916             char[] buf = new char[1024];
2917             int numRead=0;
2918             while((numRead=reader.read(buf)) != -1){
2919                 String readData = String.valueOf(buf, 0, numRead);
2920                 fileData.append(readData);
2921                 buf = new char[1024];
2922             }
2923             reader.close();
2924             fileString = fileData.toString();
2925        } catch (Exception e) {
2926             debug.error(classMethod + "Error reading file : " + fileName);
2927        }
2928        return fileString;
2929    }
2930
2931    /**
2932     * Returns the properties from existing <code>AMConfig.properties</code>.
2933     *
2934     * @return the properties from existing <code>AMConfig.properties</code>.
2935     */
2936    public static Properties getServerProperties() {
2937        String fileName =
2938                basedir +
2939                File.separator + DIR_UPGRADE + File.separator +
2940                DIR_CONFIG + File.separator + BACKUP_AMCONFIG;
2941
2942        Properties properties = (Properties) propertyFileMap.get(fileName);
2943        if (properties == null) {
2944            properties = getProperties(fileName);
2945        }
2946        return properties;
2947    }
2948
2949    /**
2950     * Writes the properties from existing <code>AMConfig.properties</code>.
2951     */
2952    public static void storeProperties(Properties props) {
2953        String classMethod = "UpgradeUtils:storeProperties : ";
2954        String fileName =
2955                basedir +
2956                File.separator + DIR_UPGRADE + File.separator +
2957                DIR_CONFIG + File.separator + BACKUP_AMCONFIG;
2958        // Write properties file.
2959        try {
2960            props.store(new FileOutputStream(fileName), null);
2961            propertyFileMap.put(fileName, props);
2962        } catch (IOException e) {
2963            debug.error(classMethod +
2964            "Error writing to AMConfig.properties.bak file " + fileName);
2965        }
2966    }
2967
2968    /**
2969     * Returns the <code>serverconfig.xml</code> file contents as a string.
2970     *
2971     * @return a string representing the <code>serverconfig.xml<code> file.
2972     */
2973    public static String getServerConfigXML() {
2974        String fileName =
2975                basedir +
2976                File.separator + DIR_UPGRADE + File.separator +
2977                DIR_CONFIG + File.separator + BACKUP_SERVER_CONFIG_XML;
2978        return readFile(fileName);
2979    }
2980
2981    /**
2982     * Returns the server name.
2983     * The server name is constructed by appending the protocol , host name
2984     * and port.
2985     *
2986     * @return the server name.
2987     */
2988    public static String getServerName() {
2989        if (serverNameURL == null) {
2990            Properties amconfigProp = getServerProperties();
2991            String serverProto = amconfigProp.getProperty(SERVER_PROTO);
2992            String serverHost = amconfigProp.getProperty(SERVER_HOST);
2993            String serverPort = amconfigProp.getProperty(SERVER_PORT);
2994            serverNameURL = serverProto + "://" + serverHost + ":" + serverPort;
2995        }
2996        return serverNameURL;
2997    }
2998
2999    /**
3000     * Returns the value of the server host.
3001     * The server host is retrieved from the <code>AMConfig.properties</code>
3002     *
3003     * @return the server host value .
3004     */
3005    public static String getServerHost() {
3006        Properties amconfigProp = getServerProperties();
3007        return amconfigProp.getProperty(SERVER_HOST);
3008    }
3009
3010    /**
3011     * Creates a file.
3012     * This method is used to create the bootstrap file
3013     *
3014     * @param fileName mame of the file to be created.
3015     * @param content value to be written to the file.
3016     */
3017    public static void writeToFile(String fileName, String content) {
3018        String classMethod = "UpgradeUtils:writeToFile : ";
3019        FileWriter fout = null;
3020        try {
3021            fout = new FileWriter(fileName);
3022            fout.write(content);
3023        } catch (IOException e) {
3024            debug.error(classMethod +
3025                    "Error writing to bootstrap file " + fileName);
3026        } finally {
3027            if (fout != null) {
3028                try {
3029                    fout.close();
3030                } catch (Exception ex) {
3031                //No handling required
3032                }
3033            }
3034        }
3035    }
3036
3037    /**
3038     * Adds attribute a sub schema.
3039     *
3040     * @param serviceName name of the service
3041     * @param parentSchemaName the parent schema name.
3042     * @param subSchemaName the subschema name
3043     * @param schemaType the schema type
3044     * @param attributeSchemaFile the name of the file containing attributes
3045     *     to be added.
3046     * @throws UpgradeException if there is an error adding the attributes.
3047     */
3048    public static void addAttributeToSubSchema(
3049            String serviceName,
3050            String parentSchemaName,
3051            String subSchemaName,
3052            String schemaType,
3053            String attributeSchemaFile) throws UpgradeException {
3054        String classMethod = "UpgradeUtils:addAttributeToSubSchema : ";
3055        if (debug.messageEnabled()) {
3056            debug.message(classMethod + "Adding attribute schema : "
3057                    + attributeSchemaFile);
3058            debug.message(" to subSchema " + subSchemaName +
3059                    " to service " + serviceName);
3060        }
3061        FileInputStream fis = null;
3062        ServiceSchema ss =
3063                getServiceSchema(serviceName, parentSchemaName, schemaType);
3064
3065        try {
3066            ServiceSchema subSchema = ss.getSubSchema(subSchemaName);
3067            fis = new FileInputStream(attributeSchemaFile);
3068            subSchema.addAttributeSchema(fis);
3069        } catch (IOException ioe) {
3070            debug.error(classMethod + "File not found " + attributeSchemaFile);
3071            throw new UpgradeException(ioe.getMessage());
3072        } catch (SMSException sme) {
3073            debug.error(classMethod + "Cannot add attribute schema to : " +
3074                    serviceName, sme);
3075            throw new UpgradeException(sme.getMessage());
3076        } catch (SSOException ssoe) {
3077            debug.error(classMethod + "Invalid SSOToken : ", ssoe);
3078            throw new UpgradeException(ssoe.getMessage());
3079        } catch (Exception e) {
3080            debug.error(classMethod + "Error setting attribute schema : ", e);
3081            throw new UpgradeException(e.getMessage());
3082        }
3083    }
3084
3085    /**
3086     * Returns the value of <code>sunserviceid</code> attribute of a service
3087     * sub-configuration.
3088     *
3089     * @param subConfig name of the service sub-configuration
3090     * @return string value of <code>sunserviceid</code> attribute.
3091     */
3092    static String getSunServiceID(ServiceConfig subConfig) {
3093        String classMethod = "UpgradeUtils:getSunServiceID : ";
3094        String serviceID = "";
3095        try {
3096            String dn = subConfig.getDN();
3097            ld = getLDAPConnection();
3098            LDAPEntry ld1 = ld.read(dn);
3099            LDAPAttributeSet attrSet = ld1.getAttributeSet();
3100            if (attrSet != null) {
3101                for (Enumeration enums = attrSet.getAttributes();
3102                        enums.hasMoreElements();) {
3103                    LDAPAttribute attr = (LDAPAttribute) enums.nextElement();
3104                    String attrName = attr.getName();
3105                    if ((attr != null) &&
3106                            attrName.equalsIgnoreCase(ATTR_SUNSERVICE_ID)) {
3107                        String[] value = attr.getStringValueArray();
3108                        serviceID = value[0];
3109                        break;
3110                    } else {
3111                        continue;
3112                    }
3113                }
3114            }
3115            if (debug.messageEnabled()) {
3116                debug.message(classMethod + " sunserviceID is :" + serviceID);
3117            }
3118        } catch (Exception e) {
3119            e.printStackTrace();
3120        }
3121        return serviceID;
3122    }
3123
3124    /**
3125     * Removes attributes default values from service subconfiguration.
3126     *
3127     * @param serviceName name of the service
3128     * @param sunServiceID set of service identifiers
3129     * @param realm the realm name
3130     * @param subConfigName the service sub-configuration name.
3131     * @param attributeName name of the attribute
3132     * @param defaultValues a set of values to be removed
3133     */
3134    public static void removeSubConfigAttributeDefaultValues(
3135            String serviceName,
3136            Set sunServiceID,
3137            String realm,
3138            String subConfigName,
3139            String attributeName,
3140            Set defaultValues) {
3141        String classMethod =
3142                "UpgradeUtils:removeSubConfigAttributeDefaultValues : ";
3143        try {
3144            ServiceConfigManager scm = getServiceConfigManager(serviceName);
3145            ServiceConfig sc = scm.getOrganizationConfig(realm, null);
3146            ServiceConfig subConfig = sc.getSubConfig(subConfigName);
3147            String serviceID = getSunServiceID(subConfig);
3148            if (debug.messageEnabled()) {
3149                debug.message(classMethod + "sunServiceID :" + sunServiceID);
3150                debug.message(classMethod + "serviceID :" + serviceID);
3151                debug.message(classMethod + "subConfigName :" + subConfigName);
3152                debug.message(classMethod + "Attribute Name :" + attributeName);
3153                debug.message(classMethod + "Default Values :" + defaultValues);
3154            }
3155            if (sunServiceID.contains(serviceID)) {
3156                Set valSet = getExistingValues(subConfig,
3157                        attributeName, defaultValues);
3158                if (debug.messageEnabled()) {
3159                    debug.message(classMethod +
3160                            "Values to be removed" + valSet);
3161                }
3162                subConfig.removeAttributeValues(attributeName, valSet);
3163            }
3164        } catch (SSOException ssoe) {
3165            debug.error(classMethod + "Invalid SSOToken  : ", ssoe);
3166        } catch (SMSException sme) {
3167            debug.error(classMethod + "Error remove default values : ", sme);
3168        }
3169    }
3170
3171    /**
3172     * Adds defaults values to service sub-configuration
3173     *
3174     * @param serviceName the service name
3175     * @param sunServiceID set of sunservice identifiers for sub-configuration
3176     * @param realm the realm name
3177     * @param subConfigName the sub-configuration name
3178     * @param attributeName the attribute name
3179     * @param defaultValues set of default values to be updated.
3180     */
3181    public static void addSubConfigAttributeDefaultValues(
3182            String serviceName,
3183            Set sunServiceID,
3184            String realm,
3185            String subConfigName,
3186            String attributeName,
3187            Set defaultValues) {
3188        String classMethod =
3189                "UpgradeUtils:addSubConfigAttributeDefaultValues : ";
3190        try {
3191            Set oldVal = new HashSet();
3192            ServiceConfigManager scm = getServiceConfigManager(serviceName);
3193            ServiceConfig sc = scm.getOrganizationConfig(realm, null);
3194            ServiceConfig subConfig = sc.getSubConfig(subConfigName);
3195            String serviceID = getSunServiceID(subConfig);
3196            if (sunServiceID.contains(serviceID)) {
3197                Set valSet = getExistingValues(
3198                        subConfig, attributeName, defaultValues);
3199                defaultValues.removeAll(valSet);
3200                subConfig.replaceAttributeValues(
3201                        attributeName, oldVal, defaultValues);
3202            }
3203        } catch (SSOException ssoe) {
3204            debug.error(classMethod + "Invalid SSOToken", ssoe);
3205        } catch (SMSException sme) {
3206            debug.error(classMethod + "Error adding values ", sme);
3207        }
3208    }
3209
3210    /**
3211     * Removes attribute from service sub-configuration instances.
3212     *
3213     * @param serviceName the service name
3214     * @param sunServiceID set of service identifiers
3215     * @param realm the realm name
3216     * @param subConfigName the subconfig name
3217     * @param attrList a list of attributes
3218     */
3219    public static void removeSubConfigAttribute(
3220            String serviceName,
3221            Set sunServiceID,
3222            String realm,
3223            String subConfigName,
3224            List attrList) {
3225        String classMethod = "UpgradeUtils:removeSubConfigAttribute : ";
3226        try {
3227            ServiceConfigManager scm = getServiceConfigManager(serviceName);
3228            ServiceConfig sc = scm.getOrganizationConfig(realm, null);
3229            ServiceConfig subConfig = sc.getSubConfig(subConfigName);
3230            String serviceID = getSunServiceID(subConfig);
3231            if (sunServiceID.contains(serviceID)) {
3232                Iterator i = attrList.iterator();
3233                while (i.hasNext()) {
3234                    String attributeName = (String) i.next();
3235                    if (debug.messageEnabled()) {
3236                        debug.message(classMethod
3237                                + "Removing attr :" + attributeName);
3238                    }
3239                    subConfig.removeAttribute(attributeName);
3240                }
3241            }
3242        } catch (SSOException ssoe) {
3243            debug.error(classMethod + "Invalid SSO Token ", ssoe);
3244        } catch (SMSException sme) {
3245            debug.error(classMethod + "Error removing attributes : " +
3246                    attrList, sme);
3247        }
3248    }
3249
3250    /**
3251     * Removes attribute default values from service schema.
3252     *
3253     * @param serviceName the service name
3254     * @param schemaType the schema type
3255     * @param attrName name of the attribute
3256     * @param defaultValues a set of default values to be remove
3257     * @throws UpgradeException if there is an error
3258     */
3259    public static void removeAttributeDefaultValues(String serviceName,
3260            String schemaType, String attrName,
3261            Set defaultValues) throws UpgradeException {
3262        removeAttributeDefaultValues(serviceName, schemaType,
3263                attrName, defaultValues, false);
3264    }
3265
3266    /**
3267     * Removes attribute default values from service schema.
3268     *
3269     * @param serviceName the service name
3270     * @param schemaType the schema type
3271     * @param attrName name of the attribute
3272     * @param defaultValues a set of default values to be remove
3273     * @param isOrgAttrSchema boolean value true if the schema is of the type
3274     *     <code>OrganizationAttributeSchema</code>
3275     * @throws UpgradeException if there is an error
3276     */
3277    public static void removeAttributeDefaultValues(String serviceName,
3278            String schemaType, String attrName,
3279            Set defaultValues, boolean isOrgAttrSchema)
3280            throws UpgradeException {
3281        String classMethod = "UpgradeUtils:removeAttributeDefaultValues : ";
3282        ServiceSchema ss = null;
3283        if (debug.messageEnabled()) {
3284            debug.message(classMethod + "serviceName : " + serviceName);
3285            debug.message(classMethod + "schemaTpe :" + schemaType);
3286            debug.message(classMethod + "attrName : " + attrName);
3287            debug.message(classMethod + "defaltValues :" + defaultValues);
3288            debug.message(classMethod + "isOrgAttrSchema :" + isOrgAttrSchema);
3289        }
3290        try {
3291            if (isOrgAttrSchema) {
3292                ServiceSchemaManager sm =
3293                        getServiceSchemaManager(serviceName);
3294                ss = sm.getOrganizationCreationSchema();
3295            } else {
3296                ss = getServiceSchema(serviceName, null, schemaType);
3297            }
3298
3299            if (ss != null) {
3300                AttributeSchema attrSchema =
3301                        ss.getAttributeSchema(attrName);
3302                for (Iterator i = defaultValues.iterator(); i.hasNext();) {
3303                    String defaultValue = (String) i.next();
3304                    attrSchema.removeDefaultValue(defaultValue);
3305                }
3306            }
3307        } catch (SMSException sme) {
3308            debug.error(classMethod + "Error removing default values ", sme);
3309        } catch (SSOException ssoe) {
3310            debug.error(classMethod + "Invalid SSO Token", ssoe);
3311        }
3312    }
3313
3314    /**
3315     * Replaces attributes default values in service sub-configuration.
3316     *
3317     * @param serviceName name of the service
3318     * @param sunServiceID a set of subconfig service identifiers.
3319     * @param realm the realm name.
3320     * @param subConfigName the name of the service sub-configuration.
3321     * @param attributeName name of the attribute
3322     * @param oldValues set of values to be replaced.
3323     * @param newValues set of values to be added.
3324     */
3325    public static void replaceSubConfigAttributeDefaultValues(
3326            String serviceName,
3327            Set sunServiceID,
3328            String realm,
3329            String subConfigName,
3330            String attributeName,
3331            Set oldValues, Set newValues) {
3332        String classMethod =
3333                "UpgradeUtils:replaceSubConfigAttributeDefaultValues : ";
3334        try {
3335            ServiceConfigManager scm = getServiceConfigManager(serviceName);
3336            ServiceConfig sc = scm.getOrganizationConfig(realm, null);
3337            ServiceConfig subConfig = sc.getSubConfig(subConfigName);
3338            String serviceID = getSunServiceID(subConfig);
3339            if (debug.messageEnabled()) {
3340                debug.message("sunServiceID :" + sunServiceID);
3341                debug.message("serviceID :" + serviceID);
3342                debug.message("subConfigName :" + subConfigName);
3343            }
3344            if (sunServiceID.contains(serviceID)) {
3345                subConfig.replaceAttributeValues(attributeName,
3346                        oldValues, newValues);
3347            }
3348        } catch (SSOException ssoe) {
3349            debug.error(classMethod + "Invalid SSO Token: ", ssoe);
3350        } catch (SMSException sme) {
3351            debug.error(classMethod
3352                    + "Error replacing default values for attribute : "
3353                    + attributeName, sme);
3354        }
3355    }
3356
3357    /**
3358     * Returns a set of valid attributes values for an attribute.
3359     *
3360     * @param subConfig the <code>ServiceConfig</code> object.
3361     * @param attrName the attribute name.
3362     * @param defaultVal set of attribute values to validate with the
3363     *    the existing attribute values.
3364     */
3365    static Set getExistingValues(ServiceConfig subConfig,
3366            String attrName, Set defaultVal) {
3367        Set valSet = new HashSet();
3368        String classMethod = "UpgradeUtils:getExistingValues : ";
3369        try {
3370            String dn = subConfig.getDN();
3371            ld = getLDAPConnection();
3372            LDAPEntry ld1 = ld.read(dn);
3373            LDAPAttributeSet attrSet = ld1.getAttributeSet();
3374            if (attrSet != null) {
3375                for (Enumeration enums = attrSet.getAttributes();
3376                enums.hasMoreElements();) {
3377                    LDAPAttribute attr = (LDAPAttribute) enums.nextElement();
3378                    String attName = attr.getName();
3379                    if ((attName != null) &&
3380                            attName.equalsIgnoreCase(ATTR_SUN_KEY_VALUE)) {
3381                        String[] value = attr.getStringValueArray();
3382                        for (int i = 0; i < value.length; i++) {
3383                            int index = value[i].indexOf("=");
3384                            if (index != -1) {
3385                                String key = value[i].substring(0, index);
3386                                if (key.equalsIgnoreCase(attrName)) {
3387                                    String v = value[i].substring(
3388                                            index + 1, value[i].length());
3389                                    if (defaultVal.contains(v)) {
3390                                        valSet.add(v);
3391                                    }
3392                                }
3393                            }
3394                        }
3395                    } else {
3396                        continue;
3397                    }
3398                }
3399            }
3400        } catch (Exception e) {
3401            debug.error(classMethod + "Error retreving attribute values ", e);
3402        }
3403        if (debug.messageEnabled()) {
3404            debug.message(classMethod + "Default Values are :" + valSet);
3405        }
3406        return valSet;
3407    }
3408
3409    /**
3410     * Remove all default values from an attribute.
3411     *
3412     * @param serviceName name of the service
3413     * @param schemaType the schema type
3414     * @param attributeName name of the attribute
3415     * @param subSchema the sub schema name.
3416     * @throws UpgradeException if there is an error.
3417     */
3418    public static void removeAllAttributeDefaultValues(
3419            String serviceName,
3420            String schemaType,
3421            String attributeName,
3422            String subSchema) throws UpgradeException {
3423        String classMethod = "UpgradeUtils:removeAttributeDefaultValues : ";
3424        try {
3425            ServiceSchema ss =
3426                    getServiceSchema(serviceName, subSchema, schemaType);
3427            // check if service schema exists.
3428            if (ss != null) {
3429                AttributeSchema attrSchema =
3430                        ss.getAttributeSchema(attributeName);
3431                attrSchema.removeDefaultValues();
3432            }
3433        } catch (SMSException sme) {
3434            throw new UpgradeException(sme.getMessage());
3435        } catch (Exception e) {
3436            debug.error(classMethod + "Error removing default values", e);
3437            throw new UpgradeException(e.getMessage());
3438        }
3439    }
3440
3441    /**
3442     * Returns a value of an attribute.
3443     * This method assumes that the attribute is single valued.
3444     *
3445     * @param serviceName name of the service.
3446     * @param attributeName name of the attribute.
3447     * @param schemaType the schema type.
3448     * @param subSchemaName the sub schema name.
3449     * @return the value of the attribute
3450     */
3451     public static String getSubSchemaAttributeValue(
3452            String serviceName,
3453            String schemaType,
3454            String attributeName,
3455            String subSchemaName) {
3456        String classMethod = "UpgradeUtils:getSubSchemaAttributeValue :";
3457        ServiceSchema ss = null;
3458        String value = null;
3459        try {
3460            ss = getServiceSchema(serviceName, subSchemaName, schemaType);
3461            AttributeSchema attrSchema = ss.getAttributeSchema(attributeName);
3462            Set defaultVal = attrSchema.getDefaultValues();
3463            value = (String) (defaultVal.iterator().next());
3464        } catch (Exception e) {
3465            debug.error(classMethod + "cannot retrieve attribute value for " +
3466                attributeName);
3467        }
3468        return value;
3469    }
3470
3471
3472    /**
3473     * Checks if the instance is FM.
3474     *
3475     * @return true if the instance is FM.
3476     */
3477    public static boolean isFMInstance() {
3478        if (instanceType == null) {
3479            instanceType = (String) configTags.get("INSTANCE_TYPE");
3480        }
3481        return (instanceType != null && instanceType.equalsIgnoreCase("FM"));
3482   }
3483
3484    /**
3485     * Removes service schema from the config store.
3486     *
3487     * @param serviceName name of the SMS service to be deleted.
3488     * @param version the version of the service
3489     */
3490    public static void removeService(String serviceName,String version) {
3491        try {
3492            ServiceManager scm = getServiceManager();
3493            scm.removeService(serviceName,version);
3494        } catch (SSOException e) {
3495            debug.error("invalid sso token" , e);
3496        } catch (SMSException sme) {
3497            debug.error("invalid service name " , sme);
3498        } catch (Exception me) {
3499            debug.error("invalid service name " , me);
3500        }
3501     }
3502    /**
3503     * Removes service schema from the config store.
3504     *
3505     * @param serviceName name of the SMS service to be deleted.
3506     */
3507    public static void removeService(String serviceName) {
3508        removeService(serviceName,"1.0");
3509     }
3510
3511    /**
3512     * Validates if the Directory server host and port are valid.
3513     *
3514     * @param dsHost the directory server host name.
3515     * @param dsPort the directory server port name.
3516     * @return true if the host and port are valid else false.
3517     */
3518    public  static boolean isValidServer(String dsHost,String  dsPort) {
3519       boolean isValidServer = true;
3520       try {
3521            LDAPConnection ldapConn = new LDAPConnection();
3522            ldapConn.connect(dsHost,new Integer(dsPort).intValue());
3523            ldapConn.disconnect();
3524        } catch (LDAPException lde) {
3525            isValidServer =false;
3526        } catch (Exception e) {
3527            isValidServer =false;
3528        }
3529        if (!isValidServer) {
3530            System.out.println(bundle.getString("upg-error-ds-info") + "!! ");
3531        }
3532        return isValidServer;
3533    }
3534
3535    /**
3536     * Validates the Directory Server Credentials.
3537     *
3538     * @param dsHost the directory server host.
3539     * @param dsPort the directory server port.
3540     * @param bindDN the dn to bind with.
3541     * @param bindPass the password.
3542     * @return true if credentials are valid else false.
3543     */
3544    public static boolean isValidCredentials(String dsHost, String dsPort,
3545            String bindDN, String bindPass) {
3546        boolean isValidAuth = false;
3547        try {
3548            LDAPConnection ldapConn = new LDAPConnection();
3549            ldapConn.connect(dsHost, new Integer(dsPort).intValue());
3550            ldapConn.authenticate(bindDN, bindPass);
3551            ldapConn.disconnect();
3552            isValidAuth = true;
3553        } catch (Exception e) {
3554            // do nothing
3555        }
3556        if (!isValidAuth) {
3557            System.out.println(bundle.getString("upg-error-credentials")
3558                + " !! ");
3559        }
3560        return isValidAuth;
3561    }
3562
3563
3564    /**
3565     * Delete an entry, recursing if the entry has children
3566     *
3567     * @param dn DN of the entry to delete
3568     * @param ld active connection to server
3569     * @param doDelete true if the entries really
3570     * are to be deleted
3571     */
3572    public static void delete(String dn, LDAPConnection ld, boolean doDelete ) {
3573        String theDN = "";
3574        try {
3575            LDAPSearchConstraints cons = ld.getSearchConstraints();
3576            // Retrieve all results at once
3577            cons.setBatchSize( 0 );
3578             // Find all immediate child nodes; return no
3579             // attributes
3580            LDAPSearchResults res = ld.search( dn, LDAPConnection.SCOPE_ONE,
3581                "objectclass=*", new String[] {LDAPv3.NO_ATTRS}, false, cons );
3582            // Recurse on entries under this entry
3583            while ( res.hasMoreElements() ) {
3584                try {
3585                    // Next directory entry
3586                    LDAPEntry entry = res.next();
3587                    theDN = entry.getDN();
3588                    // Recurse down
3589                    delete( theDN, ld, doDelete );
3590                } catch ( LDAPException e ) {
3591                    continue;
3592                } catch ( Exception ea ) {
3593                    continue;
3594                }
3595            }
3596            // At this point, the DN represents a leaf node,
3597            // so stop recursing and delete the node
3598            try {
3599                if ( doDelete ) {
3600                    ld.delete( dn );
3601                    if (debug.messageEnabled()) {
3602                        debug.message(dn + " deleted");
3603                    }
3604                }
3605            } catch (LDAPException e) {
3606                if (debug.messageEnabled()) {
3607                    debug.message( e.toString() );
3608                }
3609            } catch( Exception e ) {
3610                if (debug.messageEnabled()) {
3611                    debug.message( e.toString() );
3612                }
3613            }
3614        } catch (Exception me) {
3615            // do nothing
3616        }
3617    }
3618
3619    /**
3620     * Creates <code>OrganizationConfiguration</code> in a service.
3621     *
3622     * @param serviceName name of the service
3623     * @param orgName name of the organization
3624     * @param attrValues map of attribute names and their values. The
3625     *        key is the attribute name a string and the values is a Set
3626     *        of values.
3627     */
3628    public static void createOrganizationConfiguration(String serviceName,
3629            String orgName,Map attrValues) {
3630        String classMethod = "UpgradeUtils:createOrganizationConfiguration: ";
3631        try {
3632            ServiceConfigManager sm = getServiceConfigManager(serviceName);
3633            sm.createOrganizationConfig(orgName,attrValues);
3634        } catch (Exception e) {
3635            debug.error(classMethod + "Error creating organization "
3636                + "configuration for " + serviceName , e);
3637        }
3638    }
3639
3640    /**
3641     * Adds SubConfiguration to an existing subconfiguration in a service.
3642     *
3643     * @param serviceName the service name
3644     * @param parentConfigName the name of parent sub configuration.
3645     * @param subConfigName the subconfig name
3646     * @param subConfigID the subconfig id
3647     * @param attrValues a map of attribute value pairs to be added to the
3648     *        subconfig.
3649     * @param priority the priority value
3650     * @throws UpgradeException if there is an error.
3651     */
3652    public static void addSubConfig(
3653            String serviceName,
3654            String parentConfigName,
3655            String subConfigName,
3656            String subConfigID,
3657            Map attrValues, int priority) throws UpgradeException {
3658        String classMethod = "UpgradeUtils:addSubConfig";
3659        try {
3660            ServiceConfigManager scm =
3661                    new ServiceConfigManager(serviceName, ssoToken);
3662            ServiceConfig sc = scm.getGlobalConfig(null);
3663            ServiceConfig sc1 = sc.getSubConfig(parentConfigName);
3664            if (sc != null) {
3665                sc1.addSubConfig(subConfigName,subConfigID,priority,attrValues);
3666            } else {
3667                debug.error(classMethod +
3668                        "Error adding sub cofiguration" + subConfigName);
3669                throw new UpgradeException("Error adding subconfig");
3670            }
3671        } catch (SSOException ssoe) {
3672            throw new UpgradeException(classMethod + "invalid sso token");
3673        } catch (SMSException sm) {
3674            debug.error(classMethod + "Error loading subconfig", sm);
3675            throw new UpgradeException(classMethod + "error adding subconfig");
3676        }
3677    }
3678
3679
3680     /**
3681      * Removes Condition Properties.
3682      *
3683      * @param policyName Name of Policy.
3684      * @param attributeName the name of the attribute whose default values
3685      *        needs to be updated.
3686      * @param conditionNameMap Map of condition name to map of property name to
3687      *        set of attribute values to be removed.
3688      */
3689     public static void removeDelegationCondition(String policyName,
3690         String attributeName,Map conditionNameMap) {
3691         try {
3692             PolicyManager pm = new PolicyManager(ssoToken, HIDDEN_REALM);
3693             Policy policy = pm.getPolicy(policyName);
3694
3695             for (Iterator i = conditionNameMap.keySet().iterator();i.hasNext();
3696             ) {
3697                 String condName = (String)i.next();
3698                 Condition cond = policy.getCondition(condName);
3699                 if (cond != null) {
3700                     Set removeSet = (HashSet)conditionNameMap.get(condName);
3701                     Map orig = cond.getProperties();
3702
3703                     for (Iterator j = removeSet.iterator();
3704                         j.hasNext();
3705                     ) {
3706                         String defaultValue = (String)j.next();
3707                         Set origValues = (Set)orig.get(attributeName);
3708                         if (origValues != null) {
3709                             origValues.removeAll(removeSet);
3710                         }
3711                     }
3712                     cond.setProperties(orig);
3713                     policy.replaceCondition(condName, cond);
3714                 }
3715             }
3716             pm.replacePolicy(policy);
3717         } catch (PolicyException e) {
3718             debug.error("UpgradeUtils.removeDelegationCondition", e);
3719         } catch (SSOException e) {
3720             debug.error("UpgradeUtils.removeDelegationCondition", e);
3721         }
3722     }
3723
3724     /**
3725      * Removes attribute from a condition.
3726      *
3727      * @param policyName Name of Policy.
3728      * @param attributeName the name of the attribute to be removed.
3729      * @param conditionName name of the condition
3730      */
3731    public static void removeDelegationPolicyAttribute(String policyName,
3732            String attributeName ,String conditionName) {
3733        String classMethod = "UpgradeUtils:removeDelegationPolicyAttribute";
3734        try {
3735            PolicyManager pm = new PolicyManager(ssoToken,HIDDEN_REALM);
3736            Policy policy = pm.getPolicy(policyName);
3737
3738            Condition cond = policy.getCondition(conditionName);
3739            HashMap newMap=new HashMap();
3740            if (cond != null) {
3741                Map orig = cond.getProperties();
3742                Iterator i = (orig.keySet()).iterator();
3743                while (i.hasNext()) {
3744                    String key = (String)i.next();
3745                    if (!key.equals(attributeName)) {
3746                        HashSet values = (HashSet)orig.get(key);
3747                        newMap.put(key,values);
3748                    }
3749                 }
3750
3751                if (debug.messageEnabled()) {
3752                    debug.message(classMethod + "attributes :" + newMap);
3753                }
3754                cond.setProperties(newMap);
3755                policy.replaceCondition(conditionName, cond);
3756             }
3757             pm.replacePolicy(policy);
3758         } catch (PolicyException e) {
3759             debug.error(classMethod,e);
3760         } catch (SSOException e) {
3761             debug.error(classMethod,e);
3762         }
3763    }
3764
3765    /**
3766     * Looks for a key in the referenced resource bundle, then tokenizes the value and converts it to a list.
3767     *
3768     * @param bundle The name of the bundle we need to look up the key.
3769     * @param key The key that needs to be looked up.
3770     * @return The parsed in values in a list.
3771     */
3772    public static List<String> getPropertyValues(String bundle, String key) {
3773        List<String> ret = new ArrayList<String>();
3774        ResourceBundle rb = ResourceBundle.getBundle(bundle);
3775        String names = rb.getString(key);
3776        StringTokenizer st = new StringTokenizer(names);
3777
3778        while (st.hasMoreTokens()) {
3779            ret.add(st.nextToken());
3780        }
3781        return ret;
3782    }
3783
3784    /**
3785     * Adds a new Schema to an already existing service.
3786     *
3787     * @param serviceName The name of the service that needs to be extended.
3788     * @param schemaChanges A "container" object holding the details of the new schema.
3789     * @param adminToken An admin token.
3790     * @throws UpgradeException If there was an error while trying to add the new schema to the service.
3791     */
3792    public static void addNewSchema(String serviceName, SchemaUpgradeWrapper schemaChanges, SSOToken adminToken)
3793            throws UpgradeException {
3794        try {
3795            ServiceSchemaManager ssm = new ServiceSchemaManager(serviceName, adminToken);
3796            InputStream schemaStream = ssm.getSchema();
3797            Document dom = XMLUtils.toDOMDocument(schemaStream, debug);
3798            NodeList schemaElements = dom.getElementsByTagName("Schema");
3799            String schemaName = schemaChanges.getNewSchema().getSchemaName();
3800            debug.message("Adding new " + schemaName + " schema to " + serviceName);
3801            if (schemaElements.getLength() == 1) {
3802                Node schemaElement = schemaElements.item(0);
3803                NodeList schemas = schemaElement.getChildNodes();
3804                Node newNextSibling = null;
3805                int idx = SCHEMA_ORDER.indexOf(schemaName);
3806                for (int i = 0; i < schemas.getLength(); i++) {
3807                    Node node = schemas.item(i);
3808                    int currentIdx = SCHEMA_ORDER.indexOf(node.getNodeName());
3809                    if (currentIdx > idx) {
3810                        newNextSibling = node;
3811                        break;
3812                    }
3813                }
3814                String xml = "<" + schemaName + "></" + schemaName + ">";
3815                Document doc = XMLUtils.toDOMDocument(xml, debug);
3816                for (AttributeSchemaImpl attr : schemaChanges.getNewSchema().getAttributes()) {
3817                    Node imported = doc.importNode(attr.getAttributeSchemaNode(), true);
3818                    doc.getDocumentElement().appendChild(imported);
3819                }
3820                Node schemaNode = dom.importNode(doc.getDocumentElement(), true);
3821                schemaElement.insertBefore(schemaNode, newNextSibling);
3822                InputStream is = new ByteArrayInputStream(XMLUtils.print(dom.getDocumentElement()).getBytes());
3823                ssm.replaceSchema(is);
3824            } else {
3825                debug.error("Unexpected number of Schema element in service XML for " + serviceName
3826                        + "\n" + XMLUtils.print(dom));
3827                throw new UpgradeException("Unexpected number of Schema element in service XML for " + serviceName);
3828            }
3829        } catch (Exception ex) {
3830            UpgradeProgress.reportEnd("upgrade.failed");
3831            debug.error("An error occurred while trying to add new schema to service: " + serviceName, ex);
3832            throw new UpgradeException(ex);
3833        }
3834    }
3835}