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




























































Copyright © 2010-2017, ForgeRock All Rights Reserved.