Exemple #1
0
/*
 *	HTTP stream opener
 *      open an https input stream given a URL
 */
public class Handler extends sun.net.www.protocol.https.Handler {
  private static Debug debug = Debug.getInstance("amJSSE");

  /** Constructor */
  public Handler() {
    super();
    Https.init();
  }

  /**
   * Constructor
   *
   * @param proxy
   * @param port
   */
  public Handler(String proxy, int port) {
    super(proxy, port);
    Https.init();
  }

  /**
   * Constructor
   *
   * @param alias certificate alias for client certificate used in the https connection if client
   *     auth is required
   */
  public Handler(String alias) {
    super();
    Https.init(alias);
    if (debug.messageEnabled()) {
      debug.message("certAlias --> " + alias);
    }
  }
}
Exemple #2
0
/** The <code>PAOSUtils</code> contains utility methods for PAOS implementation. */
public class PAOSUtils {
  public static Debug debug = Debug.getInstance("libIDWSF");

  public static final String BUNDLE_NAME = "libPAOS";

  public static ResourceBundle bundle = Locale.getInstallResourceBundle(BUNDLE_NAME);
}
  public static int rebuildIndex(Map map) throws Exception {
    int ret = 0;
    shutdownServer("Rebuild index");
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);

    String[] args = {
      "--configClass",
      "org.opends.server.extensions.ConfigFileHandler",
      "--configFile",
      getOpenDJConfigFile(map),
      "--baseDN",
      (String) map.get(SetupConstants.CONFIG_VAR_ROOT_SUFFIX),
      "--rebuildAll"
    };
    OutputStream bos = new ByteArrayOutputStream();
    OutputStream boe = new ByteArrayOutputStream();
    TimeThread.start();
    ret = RebuildIndex.mainRebuildIndex(args, true, bos, boe);
    TimeThread.stop();
    String outStr = bos.toString();
    String errStr = boe.toString();
    if (errStr.length() != 0) {
      debug.error("EmbeddedOpenDS:rebuildIndex:stderr=" + errStr);
    }
    if (debug.messageEnabled()) {
      String msg = "msg=Rebuild complete.";
      int idx = outStr.indexOf(msg);
      if (idx >= 0) {
        debug.message("EmbeddedOpenDS:rebuildIndex: " + "Rebuild Status: " + outStr.substring(idx));
      }
      debug.message("EmbeddedOpenDS:rebuildIndex:Result:" + outStr);
    }
    startServer(getOpenDJBaseDir(map));
    return ret;
  }
Exemple #4
0
  static {
    String status = SystemProperties.get(Constants.AM_LOGSTATUS, "INACTIVE");
    if ("ACTIVE".equalsIgnoreCase(status)) {
      logStatus = true;
    }

    // Get Directory Port value
    try {
      directoryPort = Integer.parseInt(SystemProperties.get(Constants.AM_DIRECTORY_PORT));
    } catch (java.lang.NumberFormatException nfex) {
      directoryPort = 0;
    }

    // Get Session store
    String useHttpSessionStr = SystemProperties.get(ISAuthConstants.SESSION_STORE);
    if (useHttpSessionStr != null && useHttpSessionStr.equalsIgnoreCase("HttpSession")) {
      useHttpSession = true;
    }

    debug = Debug.getInstance(BUNDLE_NAME);
    if (debug.messageEnabled()) {
      debug.message("Directory Host: " + directoryHostName + "\nDirectory PORT : " + directoryPort);
      debug.message("Session store using " + useHttpSessionStr);
    }
  }
/**
 * Set a session property on successful authentication. If authentication fails, log a debug
 * message.
 */
public class SamplePAP implements AMPostAuthProcessInterface {
  private static final String PROP_NAME = "MyProperty";
  private static final String PROP_VALUE = "MyValue";
  private static final String DEBUG_FILE = "SamplePAP";

  protected Debug debug = Debug.getInstance(DEBUG_FILE);

  public void onLoginSuccess(
      Map requestParamsMap,
      HttpServletRequest request,
      HttpServletResponse response,
      SSOToken token)
      throws AuthenticationException {
    try {
      token.setProperty(PROP_NAME, PROP_VALUE);
    } catch (SSOException e) {
      debug.error("Unable to set property");
    }
  }

  public void onLoginFailure(
      Map requestParamsMap, HttpServletRequest request, HttpServletResponse response)
      throws AuthenticationException {
    // Not used
  }

  public void onLogout(HttpServletRequest request, HttpServletResponse response, SSOToken token)
      throws AuthenticationException {
    // Not used
  }
}
  /**
   * Get admin port of the OpenDJ server
   *
   * @param username The username of the directory admin
   * @param password The password of the directory admin
   * @param hostname The hostname of the directory server
   * @param port The port of the directory server
   * @return The admin port
   */
  public static String getAdminPort(
      String username, String password, String hostname, String port) {
    final String adminConnectorDN = "cn=Administration Connector,cn=config";
    final String[] attrs = {"ds-cfg-listen-port"};
    String adminPort = null;
    LDAPConnection ld = null;

    try {
      LDAPConnection lc = getLDAPConnection(hostname, port, username, password);

      if (lc != null) {
        LDAPEntry le = lc.read(adminConnectorDN, attrs);

        if (le != null) {
          LDAPAttribute la = le.getAttribute(attrs[0]);

          if (la != null) {
            Enumeration en = la.getStringValues();

            if (en != null && en.hasMoreElements()) {
              adminPort = (String) en.nextElement();
            }
          }
        }
      }
    } catch (Exception ex) {
      Debug.getInstance(SetupConstants.DEBUG_NAME)
          .error("EmbeddedOpenDS.getAdminPort(). Error getting admin port:", ex);
    } finally {
      disconnectDServer(ld);
    }

    return adminPort;
  }
 /** Gets list of replicated servers from local OpenDJ directory. */
 public static Set getServerSet(LDAPConnection lc) {
   final String[] attrs = {"uniqueMember"};
   Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
   try {
     if (lc != null) {
       LDAPEntry le = lc.read(replDN, attrs);
       if (le != null) {
         Set hostSet = new HashSet();
         LDAPAttribute la = le.getAttribute(attrs[0]);
         if (la != null) {
           Enumeration en = la.getStringValues();
           while (en != null && en.hasMoreElements()) {
             String val = (String) en.nextElement();
             // strip "cn="
             hostSet.add(val.substring(3, val.length()));
           }
         }
         return hostSet;
       } else {
         debug.error(
             "EmbeddedOpenDS:syncOpenDSServer():" + "Could not find trustkey for:" + replDN);
       }
     } else {
       debug.error(
           "EmbeddedOpenDS:syncOpenDSServer():" + "Could not connect to local opends instance.");
     }
   } catch (Exception ex) {
     debug.error("EmbeddedOpenDS.syncOpenDSServer()." + " Error getting replication key:", ex);
   }
   return null;
 }
  /**
   * Get replication port
   *
   * @param username
   * @param password
   * @param hostname
   * @param port
   * @return port number if replication is setup, null if not or on error.
   */
  public static String getReplicationPort(
      String username, String password, String hostname, String port) {
    final String replDN =
        "cn=replication server,cn=Multimaster Synchronization,cn=Synchronization Providers,cn=config";
    final String[] attrs = {"ds-cfg-replication-port"};
    String replPort = null;
    LDAPConnection ld = null;
    try {
      // We'll use Directory Manager
      username = "******";
      LDAPConnection lc = getLDAPConnection(hostname, port, username, password);
      if (lc != null) {
        LDAPEntry le = lc.read(replDN, attrs);
        if (le != null) {
          LDAPAttribute la = le.getAttribute(attrs[0]);
          if (la != null) {
            Enumeration en = la.getStringValues();
            if (en != null && en.hasMoreElements()) {
              replPort = (String) en.nextElement();
            }
          }
        }
      }
    } catch (Exception ex) {
      Debug.getInstance(SetupConstants.DEBUG_NAME)
          .error("EmbeddedOpenDS.getReplicationPort(). Error getting replication port:", ex);

    } finally {
      disconnectDServer(ld);
    }
    return replPort;
  }
  /**
   * Returns Replication Status by invoking OpenDJ <code>dsreplication</code> CLI
   *
   * @param port LDAP port number of embedded OpenDJ
   * @param passwd Directory Manager password
   * @param oo Standard output
   * @param err : Standard error
   * @return <code>dsreplication</code> CLI exit code.
   */
  public static int getReplicationStatus(
      String port, String passwd, OutputStream oo, OutputStream err) {
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    String baseDir = SystemProperties.get(SystemProperties.CONFIG_PATH);

    String[] statusCmd = {
      "status",
      "--no-prompt",
      "-h",
      "localhost",
      "-p",
      port,
      "--adminUID",
      "admin",
      "--adminPassword",
      passwd,
      "-s",
      "--configFile",
      baseDir + "/opends/config/config.ldif"
    };
    if (debug.messageEnabled()) {
      String dbgcmd = concat(statusCmd).replaceAll(passwd, "****");
      debug.message("EmbeddedOpenDS:getReplicationStatus:exec dsreplication :" + dbgcmd);
    }
    int ret = ReplicationCliMain.mainCLI(statusCmd, false, oo, err, null);
    if (debug.messageEnabled()) {
      debug.message("EmbeddedOpenDS:getReplicationStatus:dsreplication ret:" + ret);
    }
    return ret;
  }
Exemple #10
0
  /**
   * Runs the OpenDJ setup command to create our instance
   *
   * @param map The map of configuration options
   * @throws Exception upon encountering errors.
   */
  public static void setupOpenDS(Map map) throws Exception {
    SetupProgress.reportStart("emb.setupopends", null);

    int ret = runOpenDSSetup(map);

    if (ret == 0) {
      SetupProgress.reportEnd("emb.setupopends.success", null);
      Debug.getInstance(SetupConstants.DEBUG_NAME)
          .message("EmbeddedOpenDS.setupOpenDS: OpenDS setup succeeded.");
    } else {
      Object[] params = {Integer.toString(ret)};
      SetupProgress.reportEnd("emb.setupopends.failed.param", params);
      Debug.getInstance(SetupConstants.DEBUG_NAME)
          .error("EmbeddedOpenDS.setupOpenDS. Error setting up OpenDS");
      throw new ConfiguratorException("configurator.embsetupopendsfailed");
    }
  }
Exemple #11
0
 public static void setupReplication(Map map) throws Exception {
   // Setup replication
   SetupProgress.reportStart("emb.creatingreplica", null);
   int ret = setupReplicationEnable(map);
   if (ret == 0) {
     ret = setupReplicationInitialize(map);
     SetupProgress.reportEnd("emb.success", null);
     Debug.getInstance(SetupConstants.DEBUG_NAME)
         .message("EmbeddedOpenDS.setupReplication: replication setup succeeded.");
   } else {
     Object[] params = {Integer.toString(ret)};
     SetupProgress.reportEnd("emb.failed.param", params);
     Debug.getInstance(SetupConstants.DEBUG_NAME)
         .error("EmbeddedOpenDS.setupReplication. Error setting up replication");
     throw new ConfiguratorException("configurator.embreplfailed");
   }
 }
/**
 * Responsible for creating and initialising the AuditService from JSON config.
 *
 * @since 13.0.0
 */
public class AuditServiceProviderImpl implements AuditServiceProvider {

  private static Debug debug = Debug.getInstance("amAudit");

  /** {@inheritDoc} */
  @Override
  public AuditService createAuditService() throws AuditException {

    JsonValue extendedEventTypes = readJsonFile("/org/forgerock/openam/audit/events-config.json");
    JsonValue customEventTypes = json(object());

    AuditServiceConfiguration auditServiceConfiguration = new AuditServiceConfiguration();
    JsonValue serviceConfig = readJsonFile("/org/forgerock/openam/audit/service-config.json");
    auditServiceConfiguration.setHandlerForQueries(serviceConfig.get("useForQueries").asString());

    AuditService auditService = new AuditService(extendedEventTypes, customEventTypes);
    try {
      registerCsvAuditEventHandler(auditService);
      auditService.configure(auditServiceConfiguration);
    } catch (ResourceException | AuditException e) {
      debug.error("Unable to configure AuditService", e);
      throw new RuntimeException("Unable to configure AuditService.", e);
    }
    return auditService;
  }

  private void registerCsvAuditEventHandler(AuditService auditService)
      throws ResourceException, AuditException {
    JsonValue csvConfig = readJsonFile("/org/forgerock/openam/audit/csv-handler-config.json");

    CSVAuditEventHandlerConfiguration csvHandlerConfiguration =
        new CSVAuditEventHandlerConfiguration();
    csvHandlerConfiguration.setLogDirectory(getTmpAuditDirectory());
    csvHandlerConfiguration.setRecordDelimiter(
        csvConfig.get("config").get("recordDelimiter").asString());

    CSVAuditEventHandler csvAuditEventHandler = new CSVAuditEventHandler();
    csvAuditEventHandler.configure(csvHandlerConfiguration);

    auditService.register(csvAuditEventHandler, "csv", csvConfig.get("events").asSet(String.class));
  }

  private String getTmpAuditDirectory() {
    return new File(System.getProperty("java.io.tmpdir"), "audit").getAbsolutePath();
  }

  private JsonValue readJsonFile(String path) throws AuditException {
    try {
      InputStream is = AuditServiceProviderImpl.class.getResourceAsStream(path);
      String contents = IOUtils.readStream(is);
      return JsonValueBuilder.toJsonValue(contents.replaceAll("\\s", ""));
    } catch (IOException e) {
      debug.error("Unable to read configuration file {}", path, e);
      throw new AuditException("Unable to read configuration file " + path, e);
    }
  }
}
 private synchronized void registerListeners() {
   if (!hasRegisteredListeners) {
     SSOToken adminToken =
         (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance());
     for (Iterator i = migratedServiceNames.iterator(); i.hasNext(); ) {
       try {
         ServiceConfigManager scm = new ServiceConfigManager((String) i.next(), adminToken);
         scm.addListener(instance);
       } catch (SSOException ex) {
         Debug.getInstance(SetupConstants.DEBUG_NAME)
             .error("ConfigurationObserver.registeringListeners", ex);
       } catch (SMSException ex) {
         Debug.getInstance(SetupConstants.DEBUG_NAME)
             .error("ConfigurationObserver.registeringListeners", ex);
       }
     }
     hasRegisteredListeners = true;
   }
 }
Exemple #14
0
 /**
  * Returns a one-way hash for passwd using SSHA512 scheme.
  *
  * @param p Clear password string
  * @return hash value
  */
 public static String hash(String p) {
   String str = null;
   try {
     byte[] bb = p.getBytes();
     str = SaltedSHA512PasswordStorageScheme.encodeOffline(bb);
   } catch (Exception ex) {
     Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
     debug.error("EmbeddedOpenDS.hash failed : ex=" + ex);
   }
   return str;
 }
Exemple #15
0
/**
 * DAO for getting and storing Device Print Profiles for a given user.
 *
 * @since 12.0.0
 */
public class DevicePrintDao {

  private static final String DEBUG_NAME = "amAuthDeviceIdSave";
  private static final Debug DEBUG = Debug.getInstance(DEBUG_NAME);

  static final ObjectMapper MAPPER = new ObjectMapper();
  private static final String LDAP_DEVICE_PRINT_ATTRIBUTE_NAME = "devicePrintProfiles";

  /**
   * Gets the Device Print Profiles for the specified user.
   *
   * @param amIdentity The user's identity.
   * @return A {@code List} of the user's device print profiles.
   * @throws IdRepoException If there is a problem getting the device print profiles from LDAP.
   * @throws SSOException If there is a problem getting the device print profiles from LDAP.
   * @throws IOException If there is a problem parsing the device print profiles.
   */
  List<Map<String, Object>> getProfiles(AMIdentityWrapper amIdentity)
      throws IdRepoException, SSOException, IOException {

    Set<String> set = (Set<String>) amIdentity.getAttribute(LDAP_DEVICE_PRINT_ATTRIBUTE_NAME);
    List<Map<String, Object>> profiles = new ArrayList<Map<String, Object>>();
    for (String profile : set) {
      profiles.add(MAPPER.readValue(profile, Map.class));
    }
    return profiles;
  }

  /**
   * Stores the given Device Print Profiles for the specified user.
   *
   * @param amIdentity The user's identity.
   * @param profiles The {@code List} of the user's device print profiles.
   */
  void saveProfiles(AMIdentityWrapper amIdentity, List<Map<String, Object>> profiles) {
    try {
      Set<String> vals = new HashSet<String>();
      for (Map<String, Object> profile : profiles) {
        StringWriter writer = new StringWriter();
        MAPPER.writeValue(writer, profile);
        vals.add(writer.toString());
      }

      Map<String, Set> profilesMap = new HashMap<String, Set>();
      profilesMap.put(LDAP_DEVICE_PRINT_ATTRIBUTE_NAME, vals);

      amIdentity.setAttributes(profilesMap);
      amIdentity.store();
      DEBUG.message("Profiles stored");
    } catch (Exception e) {
      DEBUG.error("Could not store profiles. " + e);
    }
  }
}
 private void getInstanceProperties(SSOToken ssoToken) {
   try {
     Set serverSet = ServerConfiguration.getServers(ssoToken);
     for (Iterator<String> items = serverSet.iterator(); items.hasNext(); ) {
       String server = items.next();
       Properties sProps = ServerConfiguration.getServerInstance(ssoToken, server);
       printProperties(sProps, server);
     }
   } catch (Exception e) {
     Debug.getInstance(DEBUG_NAME)
         .error("ServerConfigurationReport.getInstanceProperties: " + "Exception", e);
   }
 }
Exemple #17
0
 /**
  * Gracefully shuts down the embedded OpenDJ instance.
  *
  * @param reason string representing reason why shutdown was called.
  * @throws Exception on encountering errors.
  */
 public static void shutdownServer(String reason) throws Exception {
   Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
   if (isStarted()) {
     debug.message("EmbeddedOpenDS.shutdown server...");
     DirectoryServer.shutDown("com.sun.identity.setup.EmbeddedOpenDS", Message.EMPTY);
     int sleepcount = 0;
     while (DirectoryServer.isRunning() && (sleepcount < 60)) {
       sleepcount++;
       Thread.sleep(1000);
     }
     serverStarted = false;
     debug.message("EmbeddedOpenDS.shutdown server success.");
   }
 }
Exemple #18
0
 /**
  * Helper method to return Ldap connection to a embedded OpenDJ server.
  *
  * @return Ldap connection
  */
 private static LDAPConnection getLDAPConnection(
     String dsHostName, String dsPort, String dsManager, String dsAdminPwd) {
   LDAPConnection ld = null;
   try {
     int dsPortInt = Integer.parseInt(dsPort);
     ld = new LDAPConnection();
     ld.setConnectTimeout(300);
     ld.connect(3, dsHostName, dsPortInt, dsManager, dsAdminPwd);
   } catch (LDAPException ex) {
     Debug.getInstance(SetupConstants.DEBUG_NAME)
         .error("EmbeddedOpenDS.setup(). Error getting LDAPConnection:", ex);
   }
   return ld;
 }
Exemple #19
0
 /**
  * Default Constructor
  *
  * @param realm in which emails service shall be created
  */
 public MailServerImpl(String realm) {
   debug = Debug.getInstance("amMailServer");
   sendMail = new AMSendMail();
   try {
     mgr =
         new ServiceConfigManager(
             (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance()),
             SERVICE_NAME,
             SERVICE_VERSION);
     scm = mgr.getOrganizationConfig(realm, null);
     options = scm.getAttributes();
   } catch (Exception e) {
     debug.error("Cannot get ServiceConfigManager", e);
   }
 }
Exemple #20
0
 /** Removes host:port from OpenDJ replication */
 public static void delOpenDSServer(LDAPConnection lc, String delServer) {
   String replServerDN = "cn=" + delServer + ",cn=Servers,cn=admin data";
   final String[] attrs = {"ds-cfg-key-id"};
   Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
   if (lc == null) {
     debug.error(
         "EmbeddedOpenDS:syncOpenDSServer():"
             + "Could not connect to local OpenDJ instance."
             + replServerDN);
     return;
   }
   String trustKey = null;
   try {
     LDAPEntry le = lc.read(replServerDN, attrs);
     if (le != null) {
       LDAPAttribute la = le.getAttribute(attrs[0]);
       if (la != null) {
         Enumeration en = la.getStringValues();
         if (en != null && en.hasMoreElements()) {
           trustKey = (String) en.nextElement();
         }
       }
       String keyDN = "ds-cfg-key-id=" + trustKey + ",cn=instance keys,cn=admin data";
       lc.delete(keyDN);
     } else {
       debug.error(
           "EmbeddedOpenDS:syncOpenDSServer():" + "Could not find trustkey for:" + replServerDN);
     }
   } catch (Exception ex) {
     debug.error("EmbeddedOpenDS.syncOpenDSServer()." + " Error getting replication key:", ex);
   }
   try {
     lc.delete(replServerDN);
   } catch (Exception ex) {
     debug.error(
         "EmbeddedOpenDS.syncOpenDSServer()."
             + " Error getting deleting server entry:"
             + replServerDN,
         ex);
   }
   try {
     LDAPAttribute attr = new LDAPAttribute("uniqueMember", "cn=" + delServer);
     LDAPModification mod = new LDAPModification(LDAPModification.DELETE, attr);
     lc.modify(replDN, mod);
   } catch (Exception ex) {
     debug.error("EmbeddedOpenDS.syncOpenDSServer()." + " Error getting removing :" + replDN, ex);
   }
 }
Exemple #21
0
  /**
   * Starts the embedded <code>OpenDJ</code> instance.
   *
   * @param odsRoot File system directory where <code>OpenDJ</code> is installed.
   * @throws Exception upon encountering errors.
   */
  public static void startServer(String odsRoot) throws Exception {
    if (isStarted()) {
      return;
    }
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    debug.message("EmbeddedOpenDS.startServer(" + odsRoot + ")");

    DirectoryEnvironmentConfig config = new DirectoryEnvironmentConfig();
    config.setServerRoot(new File(odsRoot));
    config.setForceDaemonThreads(true);
    config.setConfigClass(ConfigFileHandler.class);
    config.setConfigFile(new File(odsRoot + "/config", "config.ldif"));
    debug.message("EmbeddedOpenDS.startServer:starting DS Server...");
    EmbeddedUtils.startServer(config);
    debug.message("...EmbeddedOpenDS.startServer:DS Server started.");

    int sleepcount = 0;
    while (!EmbeddedUtils.isRunning() && (sleepcount < 60)) {
      sleepcount++;
      SetupProgress.reportStart("emb.waitingforstarted", null);
      Thread.sleep(1000);
    }

    if (EmbeddedUtils.isRunning()) {
      SetupProgress.reportEnd("emb.success", null);
    } else {
      SetupProgress.reportEnd("emb.failed", null);
    }

    serverStarted = true;

    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();

    shutdownMan.addShutdownListener(
        new ShutdownListener() {
          public void shutdown() {
            try {
              shutdownServer("Graceful Shutdown");
            } catch (Exception ex) {
              Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
              debug.error("EmbeddedOpenDS:shutdown hook failed", ex);
            }
          }
        },
        ShutdownPriority.LOWEST);
  }
/**
 * Provides the ability to query a collection of OpenAM servers for Session information. Uses the
 * SessionQueryFactory to determine the most appropriate mechanism for performing the query and
 * handles any complexity around querying Sessions.
 *
 * <p>This manager should easily be expanded to support new functions like 'Session Count' or 'Get
 * Sessions for User'.
 *
 * @author [email protected]
 */
public class SessionQueryManager {

  private static Debug debug = Debug.getInstance("frRest");

  private SessionQueryFactory queryFactory;

  /**
   * Intialise the SessionQueryManager and provide the OpenAM server ids that it should apply to.
   *
   * @param queryFactory Non null instance.
   */
  public SessionQueryManager(SessionQueryFactory queryFactory) {
    this.queryFactory = queryFactory;
  }

  /**
   * Query all servers allocated to this SessionQueryManager for their Sessions.
   *
   * @param serverIds One or more server id's. Typically this value can be generated using {@link
   *     com.iplanet.services.naming.WebtopNaming#getAllServerIDs()} which will provide all server
   *     id's known to OpenAM.
   * @return Returns all sessions across all servers.
   */
  public Collection<SessionInfo> getAllSessions(Collection<String> serverIds) {
    // impl note, this could be a Map of Server -> Sessions

    List<SessionInfo> sessions = new LinkedList<SessionInfo>();

    for (String server : serverIds) {
      SessionQueryType queryType = queryFactory.getSessionQueryType(server);

      Collection<SessionInfo> queriedSessions = queryType.getAllSessions();

      if (debug.messageEnabled()) {
        debug.message(
            MessageFormat.format(
                "SessionQueryManager#getAllSessions() :: Queried {0} from: {1}",
                queriedSessions.size(), server));
      }

      sessions.addAll(queriedSessions);
    }

    return sessions;
  }
}
  // Static Initialization Stanza.
  static {
    sessionDebug = Debug.getInstance("amSession");

    if (doRequestFlag != null) {
      if (doRequestFlag.equals("false")) doRequest = false;
    }
    if (hcPath == null) {
      String deployuri =
          SystemProperties.get(Constants.AM_SERVICES_DEPLOYMENT_DESCRIPTOR, "/openam");
      hcPath = deployuri + "/namingservice";
      if (!hcPath.startsWith("/")) {
        hcPath += "/" + hcPath;
      }

      GET_REQUEST = "GET " + hcPath + " HTTP/1.0";
    }
  } // End of Static Initialization Stanza
Exemple #24
0
public class MappingUtils {
  private static Debug debug = Debug.getInstance("amAuth");
  private static final String EQUALS = "=";

  /**
   * This method parses out the local_attribute=source_attributes as they are encapsulated in the
   * authN module configurations into a more usable, Map<String, String> format.
   *
   * @param configuredMappings The set of local=source mappings.
   * @return The derived Map instance.
   */
  public static Map<String, String> parseMappings(Set<String> configuredMappings) {
    Map<String, String> parsedMappings = new HashMap<String, String>();
    for (String mapping : configuredMappings) {
      if (mapping.indexOf(EQUALS) == -1) {
        continue;
      }
      StringTokenizer tokenizer = new StringTokenizer(mapping, EQUALS);
      final String key = tokenizer.nextToken();
      final String value = tokenizer.nextToken();
      /*
      The ldap_attr=spource_attr mapping is user-generated, so I want to warn about duplicate entries. In a
      HashMap, repeated insertion of the same key will over-write previous entries, but I want to warn about
      duplicate entries, and will persist the first entry.
       */
      if (!parsedMappings.containsKey(key)) {
        parsedMappings.put(key, value);
      } else {
        if (debug.warningEnabled()) {
          debug.warning(
              "In MappingUtils.parseMappings, the user-entered attribute mappings contain "
                  + "duplicate entries. The first entry will be preserved: "
                  + configuredMappings);
        }
      }
    }
    if (parsedMappings.isEmpty()) {
      throw new IllegalArgumentException(
          "The mapping Set does not contain any mappings in format "
              + "local_attribute=source_attribute.");
    }
    return Collections.unmodifiableMap(parsedMappings);
  }
}
Exemple #25
0
  /**
   * Utility function to preload data in the embedded instance. Must be called when the directory
   * instance is shutdown.
   *
   * @param odsRoot Local directory where <code>OpenDJ</code> is installed.
   * @param ldif Full path of the ldif file to be loaded.
   */
  public static int loadLDIF(Map map, String odsRoot, String ldif) {
    int ret = 0;

    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    File ldifFile = new File(ldif);
    if (!ldifFile.exists()) {
      debug.error("LDIF File:" + ldifFile.getAbsolutePath() + " does not exist, unable to load!");
      return -1;
    }
    try {
      if (debug.messageEnabled()) {
        debug.message("EmbeddedOpenDS:loadLDIF(" + ldif + ")");
      }

      String[] args1 = {
        "-C", // 0
        "org.opends.server.extensions.ConfigFileHandler", // 1
        "-f", // 2
        odsRoot + "/config/config.ldif", // 3
        "-n", // 4
        "userRoot", // 5
        "-l", // 6
        ldif, // 7
        "--trustAll", // 8
        "-D", // 9
        "cn=Directory Manager", // 10
        "-w", // 11
        "password" // 12
      };
      args1[10] = (String) map.get(SetupConstants.CONFIG_VAR_DS_MGR_DN);
      args1[12] = (String) map.get(SetupConstants.CONFIG_VAR_DS_MGR_PWD);
      ret =
          org.opends.server.tools.ImportLDIF.mainImportLDIF(
              args1, false, SetupProgress.getOutputStream(), SetupProgress.getOutputStream());

      if (debug.messageEnabled()) {
        debug.message("EmbeddedOpenDS:loadLDIF Success");
      }
    } catch (Exception ex) {
      debug.error("EmbeddedOpenDS:loadLDIF:ex=", ex);
    }

    return ret;
  }
Exemple #26
0
  public static String getOpenDSVersion() {
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    String odsRoot = AMSetupServlet.getBaseDir() + "/" + SetupConstants.SMS_OPENDS_DATASTORE;
    String version = "unknown";

    File configLdif = new File(odsRoot + OPENDS_UPGRADE_DIR);

    File buildInfo = new File(odsRoot + "/" + "config" + "/" + SetupConstants.OPENDJ_BUILDINFO);

    if (configLdif.exists() && configLdif.isDirectory()) {
      String[] configFile =
          configLdif.list(
              new FilenameFilter() {
                // @Override -- Not Allowed Here.
                public boolean accept(File dir, String name) {
                  return name.startsWith(OPENDS_CONFIG_LDIF);
                }
              });

      if (configFile.length != 0) {
        version = configFile[0].substring(configFile[0].lastIndexOf('.') + 1);
      } else {
        debug.error("Unable to determine OpenDJ version");
      }
    } else if (buildInfo.exists() && buildInfo.canRead() && buildInfo.isFile()) {
      String buildInfoVersionText = getOpenDJBuildInfo(buildInfo);
      if ((buildInfoVersionText != null) && (!buildInfoVersionText.isEmpty())) {
        version = buildInfoVersionText.trim();
      } else {
        debug.error("Unable to determine OpenDJ version");
      }
    } else {
      if (debug.warningEnabled()) {
        debug.warning("Unable to determine OpenDJ version; could be pre-config");
      }
    }

    if (debug.messageEnabled()) {
      debug.message("Found OpenDJ version: " + version);
    }

    return version;
  }
Exemple #27
0
 /** Create and return the system timer. */
 public static synchronized TimerPool getTimer() {
   if (instance == null) {
     debug = Debug.getInstance("SystemTimer");
     ShutdownManager shutdownMan = ShutdownManager.getInstance();
     if (shutdownMan.acquireValidLock()) {
       try {
         instance = new TimerPool("SystemTimer", 1, false, debug);
         shutdownMan.addShutdownListener(
             new ShutdownListener() {
               public void shutdown() {
                 instance.shutdown();
               }
             });
       } finally {
         shutdownMan.releaseLockAndNotify();
       }
     }
   }
   return instance;
 }
Exemple #28
0
/** Configuration values for the thread pool loaded from OpenAM's admin console constructs. */
public class ThreadPoolConfig {

  private static final Debug logger = Debug.getInstance(RadiusServerConstants.RADIUS_SERVER_LOGGER);

  private static final int defaultCoreThreads = 2;
  private static final int defaultKeepAliveSeconds = 10;
  private static final int defaultQueueSize = 10;

  private final int keepAliveSeconds;
  private final int queueSize;
  private final int maxThreads;
  private final int coreThreads;

  /**
   * Constructs a ThreadPoolConfig.
   *
   * @param core -the core number of threads required.
   * @param max - the max number of threads to be used by the thread pool
   * @param queueSize - the size of the queue
   * @param keepAliveSeconds - when the number of threads is greater than the core, this is the
   *     maximum time that excess idle threads will wait for new tasks before terminating.
   */
  public ThreadPoolConfig(int core, int max, int queueSize, int keepAliveSeconds) {
    if (core < 2) {
      this.coreThreads = defaultCoreThreads;
      logger.warning(
          "System configured to used invalid Radius Thread Pool Core size of "
              + core
              + ". Using the value of "
              + defaultCoreThreads
              + " instead.");
    } else {
      this.coreThreads = core;
    }

    if (max < this.coreThreads) {
      this.maxThreads = coreThreads;
      logger.warning(
          "System configured to use Radius Server 'Thread Pool Max Size' that is less than 'Thread "
              + "Pool Core Size. Using size equal to Core Size - i.e. a static pool of size "
              + coreThreads);
    } else {
      this.maxThreads = max;
    }

    if (queueSize < 1 || queueSize > 1000) {
      this.queueSize = defaultQueueSize;
      logger.warning(
          "System configured to use an invalid Radius Server 'Thread Pool Queue Size' value of '"
              + queueSize
              + "'. Using the default value of '"
              + defaultQueueSize
              + "' instead.");
    } else {
      this.queueSize = queueSize;
    }

    if (keepAliveSeconds < 1 || keepAliveSeconds > 3600) {
      this.keepAliveSeconds = defaultKeepAliveSeconds;
      logger.warning(
          "System configured to use an invalid Radius Server 'Thread Pool Keep-Alive Seconds' value of"
              + " '"
              + keepAliveSeconds
              + "'. Using the default value of '"
              + defaultKeepAliveSeconds
              + "' instead.");
    } else {
      this.keepAliveSeconds = keepAliveSeconds;
    }
  }

  /**
   * Return the number of seconds that, when the number of threads is greater than the core, is the
   * maximum time that excess idle threads will wait for new tasks before terminating.
   *
   * @return the keepAliveSeconds
   */
  public int getKeepAliveSeconds() {
    return this.keepAliveSeconds;
  }

  /**
   * Return the size of the queue used to queue work items.
   *
   * @return the queueSize
   */
  public int getQueueSize() {
    return this.queueSize;
  }

  /**
   * Get the maximum number of threads the thread pool can hold.
   *
   * @return the maxThreads
   */
  public int getMaxThreads() {
    return this.maxThreads;
  }

  /**
   * Get the number of core threads - the thread pool should keep this many threads around even if
   * they have no work to do.
   *
   * @return the coreThreads
   */
  public int getCoreThreads() {
    return this.coreThreads;
  }

  @Override
  public boolean equals(Object o) {
    if (o == null || !(o instanceof ThreadPoolConfig)) {
      return false;
    }
    final ThreadPoolConfig t = (ThreadPoolConfig) o;
    return keepAliveSeconds == t.keepAliveSeconds
        && queueSize == t.queueSize
        && maxThreads == t.maxThreads
        && coreThreads == t.coreThreads;
  }

  // don't really need to being a good citizen
  @Override
  public int hashCode() {
    return keepAliveSeconds + queueSize + maxThreads + coreThreads;
  }
}
Exemple #29
0
public class EncryptionUtils {

  public static Debug debug = Debug.getInstance("libEncryption");
  public static final String BUNDLE_NAME = "libEncryption";
  public static ResourceBundle bundle = Locale.getInstallResourceBundle(BUNDLE_NAME);
}
Exemple #30
0
  /** Synchronizes replication domain info with current list of OpenAM servers. */
  public static boolean syncReplicatedDomains(Set currServerSet, String port, String passwd) {
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    debug.message("EmbeddedOpenDS:syncReplication:Domains:started");
    String[] args = {
      "-p",
      port, // 1 : ds port num
      "-h",
      "localhost",
      "-D",
      "cn=directory manager",
      "-w",
      passwd, // 7 : password
      "list-replication-domains",
      "--provider-name",
      "Multimaster Synchronization",
      "--property",
      "replication-server",
      "--no-prompt",
      "--trustAll"
    };
    if (debug.messageEnabled()) {
      String dbgcmd = concat(args).replaceAll(passwd, "****");
      debug.message("EmbeddedOpenDS:syncReplication:exec dsconfig:" + dbgcmd);
    }
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ByteArrayOutputStream boe = new ByteArrayOutputStream();
    DSConfig.main(args, false, bos, boe);
    String str = bos.toString();
    String stre = boe.toString();
    if (stre.length() != 0) {
      debug.error("EmbeddedOpenDS:syncReplication:stderr:" + stre);
    }
    /*
       v2.6 output example

       Replication Domain            : replication-server
       ------------------------------:---------------------------------------------
       cn=admin data                 : dj1.example.com:58989, dj2.example.com:50889
       cn=schema                     : dj1.example.com:58989, dj2.example.com:50889
       dc=openam,dc=forgerock,dc=org : dj1.example.com:58989, dj2.example.com:50889
    */

    BufferedReader brd = new BufferedReader(new StringReader(str));
    String line = null;
    try {
      line = brd.readLine(); // 1st line
      line = brd.readLine(); // 2nd line
      while ((line = brd.readLine()) != null) {
        try {
          int dcolon = line.indexOf(':');
          String domainname = line.substring(0, dcolon).trim();
          int stcolon = dcolon + 1;
          String replservers = line.substring(stcolon + 1);
          if (debug.messageEnabled()) {
            debug.message(
                "EmbeddedOpenDS:syncRepl:domain=" + domainname + " replservers=" + replservers);
          }

          StringTokenizer stok = new StringTokenizer(replservers, ",");
          // Check if this server is part of server list
          List cmdlist = new ArrayList();
          cmdlist.add("-p");
          cmdlist.add(port);
          cmdlist.add("-h");
          cmdlist.add("localhost");
          cmdlist.add("-D");
          cmdlist.add("cn=directory manager");
          cmdlist.add("-w");
          cmdlist.add(passwd);
          cmdlist.add("--no-prompt");
          cmdlist.add("--trustAll");
          cmdlist.add("set-replication-domain-prop");
          cmdlist.add("--provider-name");
          cmdlist.add("Multimaster Synchronization");
          cmdlist.add("--domain-name");
          cmdlist.add(domainname);

          int numremoved = 0;
          while (stok.hasMoreTokens()) {
            String tok = stok.nextToken().trim();
            if (!currServerSet.contains(tok)) {
              cmdlist.add("--remove");
              cmdlist.add("replication-server:" + tok);
              numremoved++;
            }
          }
          if (numremoved > 0) {
            String[] args1 = (String[]) cmdlist.toArray(new String[cmdlist.size()]);
            if (debug.messageEnabled()) {
              String dbgcmd1 = concat(args1).replaceAll(passwd, "****");
              debug.message("EmbeddedOpenDS:syncReplication:Execute:" + dbgcmd1);
            }
            bos = new ByteArrayOutputStream();
            boe = new ByteArrayOutputStream();
            DSConfig.main(args1, false, bos, boe);
            str = bos.toString();
            stre = boe.toString();
            if (stre.length() != 0) {
              debug.error("EmbeddedOpenDS:syncRepl:stderr=" + stre);
            }
            if (debug.messageEnabled()) {
              debug.message("EmbeddedOpenDS:syncReplication:Result:" + str);
            }
          }
        } catch (Exception ex) {
          debug.error("EmbeddedOpenDS:syncReplication:Failed:", ex);
          return false;
        }
      }
    } catch (Exception ex) {
      debug.error("EmbeddedOpenDS:syncReplication:Failed:", ex);
      return false;
    }
    return true;
  }