Ejemplo n.º 1
0
  /**
   * Method which removes the DC Tree corresponding to the Org
   *
   * @param token SSOToken
   * @param orgDN String representing the DN correponding to the organization
   * @exception AMException if error occured in accessing the org corresponding to orgDN or during
   *     the removal of the dc tree corresponding to the orgDN
   */
  protected void removeDomain(SSOToken token, String orgDN) throws AMException {

    // String orgAttribute[] = {IPLANET_DOMAIN_NAME_ATTR};
    try {
      PersistentObject po = UMSObject.getObject(token, new Guid(orgDN));
      if (!(po instanceof com.iplanet.ums.Organization)) {
        if (debug.messageEnabled()) {
          debug.message("DCTree.removeDomain-> " + orgDN + " is not an organization");
        }
        return;
      }
      String domainName = getCanonicalDomain(token, orgDN);
      if (debug.messageEnabled()) {
        debug.message("DCTree.removeDomain-> " + "Obtained canon domain " + domainName);
      }
      if ((domainName != null) && (domainName.length() > 0)) {
        DomainComponentTree dcTree = new DomainComponentTree(token, new Guid(DCTREE_START_DN));
        if (debug.messageEnabled()) {
          debug.message("DCTree.removeDomain: removing domain: " + domainName);
        }
        dcTree.removeDomain(domainName);
      } else {
        if (debug.warningEnabled()) {
          debug.warning("DCTree.removeDomain(): " + " unable to get domain for " + orgDN);
        }
      }
    } catch (UMSException ue) {
      if (debug.warningEnabled()) {
        debug.warning("DCTree.removeDomain(): ", ue);
      }
    }
  }
Ejemplo n.º 2
0
  static void initialize(SSOToken token) throws SMSException, SSOException {
    // Validate SSOToken
    SMSEntry.validateToken(token);

    // Check if already initialized
    if (initialized) return;
    // Initilaize the parameters
    try {
      // Get the service names and cache it
      serviceNames = CachedSubEntries.getInstance(token, serviceDN);
      if (serviceNames.getSMSEntry().isNewEntry()) {
        if (debug.warningEnabled()) {
          debug.warning("SeviceManager:: Root service node " + "does not exists: " + serviceDN);
        }
        String[] msgs = new String[1];
        msgs[0] = serviceDN;
        throw (new SMSException(
            IUMSConstants.UMS_BUNDLE_NAME, IUMSConstants.SMS_services_node_does_not_exist, msgs));
      }
    } catch (SMSException e) {
      debug.error("ServiceManager::unable to get " + "services node: " + serviceDN, e);
      throw (e);
    }
    // Check if realm is enabled and set appropriate flags
    checkFlags(token);
    initialized = true;
  }
Ejemplo n.º 3
0
 /**
  * removes the listener from the list of Persistent Search listeners of the asynchronous seach for
  * the given search ID.
  *
  * @param request The request returned by the addListener
  * @supported.api
  */
 protected void removeListener(Request request) {
   LDAPConnection connection = request.getLDAPConnection();
   if (connection != null) {
     if (debugger.messageEnabled()) {
       debugger.message(
           "EventService.removeListener(): Removing "
               + "listener requestID: "
               + request.getRequestID()
               + " Listener: "
               + request.getListener());
     }
     try {
       if ((connection != null) && (connection.isConnected())) {
         connection.abandon(request.getId());
         connection.disconnect();
       }
     } catch (LDAPException le) {
       // Might have to check the reset codes and try to reset
       if (debugger.warningEnabled()) {
         debugger.warning(
             "EventService.removeListener(): " + "LDAPException, when trying to remove listener",
             le);
       }
     }
   }
 }
Ejemplo n.º 4
0
 /**
  * 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);
 }
 /**
  * Adds Compliance Mode Filters to the original filter if running in Compliance mode. The addition
  * of filters can be by-passed by setting the ignoreComplianceFilter to true.
  */
 private static String addComplianceModeFilters(
     String originalFilter, int objectType, boolean ignoreComplianceFilter) {
   try {
     // Modify search filters if complaince user deletion enabled
     // Ignore if explicitly specified.
     String modifiedFilter = originalFilter;
     if (!ignoreComplianceFilter && AMCompliance.isComplianceUserDeletionEnabled()) {
       StringBuilder sb = new StringBuilder();
       switch (objectType) {
         case AMObject.USER:
           sb.append("(&").append(originalFilter);
           sb.append("(!(inetuserstatus=deleted)))");
           modifiedFilter = sb.toString();
           break;
         case AMObject.ORGANIZATION:
           sb.append("(&").append(originalFilter);
           sb.append("(!(inetdomainstatus=deleted)))");
           modifiedFilter = sb.toString();
           break;
         case AMObject.STATIC_GROUP:
         case AMObject.DYNAMIC_GROUP:
         case AMObject.ASSIGNABLE_DYNAMIC_GROUP:
         case AMObject.GROUP:
           sb.append("(&").append(originalFilter);
           sb.append("(!(inetgroupstatus=deleted)))");
           modifiedFilter = sb.toString();
           break;
       }
       if (debug.messageEnabled()) {
         debug.message(
             "AMSearchFilterManager."
                 + ""
                 + "addComplainceModeFilters() - objectType = "
                 + objectType
                 + ", Original Filter = "
                 + originalFilter
                 + ", Modified Filter = "
                 + modifiedFilter);
       }
       return modifiedFilter;
     }
   } catch (AMException ae) {
     if (debug.warningEnabled()) {
       debug.warning(
           "AMSearchFilterManager."
               + "addComplianceModeFilters() Unable to determine if "
               + "\"User Compliance deletion mode\" is enabled or "
               + "disabled. Exception : ",
           ae);
     }
   }
   return originalFilter;
 }
Ejemplo n.º 6
0
  /**
   * Returns the attribute value configured in the given entity SP or IDP configuration.
   *
   * @param realm realm name.
   * @param entityID hosted <code>EntityID</code>.
   * @param attributeName name of the attribute.
   */
  protected String getAttribute(String realm, String entityID, String attributeName) {

    if (realm == null || entityID == null || attributeName == null) {
      if (debug.messageEnabled()) {
        debug.message("DefaultAccountMapper.getAttribute: " + "null input parameters.");
      }
      return null;
    }

    try {
      BaseConfigType config = null;
      if (role.equals(IDP)) {
        config = WSFederationUtils.getMetaManager().getIDPSSOConfig(realm, entityID);
      } else {
        config = WSFederationUtils.getMetaManager().getSPSSOConfig(realm, entityID);
      }
      Map attributes = WSFederationMetaUtils.getAttributes(config);

      if (attributes == null || attributes.isEmpty()) {
        if (debug.messageEnabled()) {
          debug.message(
              "DefaultAccountMapper.getAttribute:"
                  + " attribute configuration is not defined for "
                  + "Entity "
                  + entityID
                  + " realm ="
                  + realm
                  + " role="
                  + role);
        }
        return null;
      }

      List list = (List) attributes.get(attributeName);
      if (list != null && list.size() > 0) {
        return (String) list.iterator().next();
      }

      if (debug.messageEnabled()) {
        debug.message(
            "DefaultSPAccountMapper.getAttribute: " + attributeName + " is not configured.");
      }
      return null;

    } catch (WSFederationMetaException sme) {
      if (debug.warningEnabled()) {
        debug.warning("DefaultSPAccountMapper.getAttribute:" + "Meta Exception", sme);
      }
    }
    return null;
  }
Ejemplo n.º 7
0
 /**
  * Returns all AM Server instance. Read the configured servers from platform service's <code>
  * iplanet-am-platform-server-list</code>
  */
 public static Set getAMServerInstances() {
   // Check cache
   if (accessManagerServers == null) {
     // Get AdminToken
     try {
       SSOToken token = (SSOToken) AccessController.doPrivileged(AdminTokenAction.getInstance());
       accessManagerServers = ServerConfiguration.getServers(token);
       if (debug.messageEnabled()) {
         debug.message(
             "ServiceManager.getAMServerInstances: " + "server list: " + accessManagerServers);
       }
     } catch (SMSException e) {
       if (debug.warningEnabled()) {
         debug.warning("ServiceManager.getAMServerInstances: " + "Unable to get server list", e);
       }
     } catch (SSOException e) {
       if (debug.warningEnabled()) {
         debug.warning("ServiceManager.getAMServerInstances: " + "Unable to get server list", e);
       }
     }
   }
   return (accessManagerServers == null ? new HashSet() : new HashSet(accessManagerServers));
 }
  /** Adds filters to eliminate admin groups if the Admin Group option is not enabled. */
  private static String addAdminGroupFilters(String originalFilter, String orgDN, int objectType) {
    try {
      // Filter out Admin Groups if the option is NOT enabled
      if (!AMCompliance.isAdminGroupsEnabled(orgDN)) {
        String modifiedFilter = originalFilter;
        switch (objectType) {
          case AMObject.STATIC_GROUP:
          case AMObject.DYNAMIC_GROUP:
          case AMObject.ASSIGNABLE_DYNAMIC_GROUP:
          case AMObject.GROUP:
            StringBuilder sb = new StringBuilder();
            sb.append("(&").append(originalFilter).append("(!(");
            sb.append(AMNamingAttrManager.getNamingAttr(AMObject.ASSIGNABLE_DYNAMIC_GROUP));
            sb.append("=serviceadministrators))").append("(!(");
            sb.append(AMNamingAttrManager.getNamingAttr(AMObject.ASSIGNABLE_DYNAMIC_GROUP));
            sb.append("=servicehelpdeskadministrators)))");
            modifiedFilter = sb.toString();
        }

        if (debug.messageEnabled()) {
          debug.message(
              "AMSearchFilterManager."
                  + "addAdminGroupFilters() - objectType = "
                  + objectType
                  + ", orgDN = "
                  + orgDN
                  + ", Original filter: "
                  + originalFilter
                  + ", Modified filter = "
                  + modifiedFilter);
        }
        return modifiedFilter;
      }
    } catch (AMException ae) {
      if (debug.warningEnabled()) {
        debug.warning(
            "AMSearchFilterManager.addAdminGroupFilters() "
                + "Unable to determine if \"Admin Groups\" "
                + "option is enabled or disabled. Exception : ",
            ae);
      }
    }
    return originalFilter;
  }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 10
0
  /** Pushes off to our logging subsystem. */
  private void logAccess(String resource, String operation, ServerContext context) {

    if (!context.containsContext(SSOTokenContext.class)) {
      context = new SSOTokenContext(context);
    }

    SSOTokenContext ssoTokenContext = context.asContext(SSOTokenContext.class);

    try {
      restLog.auditAccessMessage(resource, operation, ssoTokenContext.getCallerSSOToken());
    } catch (SSOException e) {
      if (debug.warningEnabled()) {
        debug.warning(
            "LoggingFluentRouter :: "
                + "Error retrieving SSO Token from provided context, forced to log user as 'null'.",
            e);
        restLog.auditAccessMessage(resource, operation, null);
      }
    }

    restLog.debugOperationAttemptAsPrincipal(resource, operation, context, null, debug);
  }
Ejemplo n.º 11
0
  /**
   * Helper function to retrieve a field from the provided request's query parameters. This exists
   * for the old-style interfaces, and takes the parameter name as an argument also.
   *
   * <p>If the queryParameters contain the "encoded" parameter, then the result is Base64 decoded
   * before being returned.
   *
   * @param request Request containing the parameters to retrieve.
   * @param paramName The name of the parameter whose value to (possibly decode) return.
   * @return The (possibly decoded) value of the paramName's key within the requests's query
   *     parameters.
   */
  public String getAndDecodeParameter(HttpServletRequest request, String paramName) {
    String value = request.getParameter(paramName);

    if (value == null) {
      return null;
    }

    String encoded = request.getParameter("encoded");
    if (Boolean.parseBoolean(encoded)) {
      String decodedParameterValue = Base64.decodeAsUTF8String(value);
      if (decodedParameterValue == null && DEBUG.warningEnabled()) {
        DEBUG.warning(
            "As parameter 'encoded' is true, parameter ['{}']='{}' should be base64 encoded",
            paramName,
            value);
      }
      return decodedParameterValue;

    } else {
      return value;
    }
  }
Ejemplo n.º 12
0
  private static int getPropertyIntValue(String key, int defaultValue) {
    int value = defaultValue;
    String valueStr = SystemProperties.get(key);
    if (valueStr != null && valueStr.trim().length() > 0) {
      try {
        value = Integer.parseInt(valueStr);
      } catch (NumberFormatException e) {
        value = defaultValue;
        if (debugger.warningEnabled()) {
          debugger.warning(
              "EventService.getPropertyIntValue(): "
                  + "Invalid value for property: "
                  + EVENT_CONNECTION_NUM_RETRIES
                  + " Defaulting to value: "
                  + defaultValue);
        }
      }
    }

    if (debugger.messageEnabled()) {
      debugger.message("EventService.getPropertyIntValue(): " + key + " = " + value);
    }
    return value;
  }
Ejemplo n.º 13
0
  /**
   * Main monitor thread loop. Wait for persistent search change notifications
   *
   * @supported.api
   */
  public void run() {
    try {
      if (debugger.messageEnabled()) {
        debugger.message(
            "EventService.run(): Event Thread is running! "
                + "No Idle timeout Set: "
                + _idleTimeOut
                + " minutes.");
      }

      boolean successState = true;
      LDAPMessage message = null;
      while (successState) {
        try {
          if (debugger.messageEnabled()) {
            debugger.message("EventService.run(): Waiting for " + "response");
          }
          synchronized (this) {
            if (_requestList.isEmpty()) {
              wait();
            }
          }
          message = _msgQueue.getResponse();
          successState = processResponse(message);
        } catch (LDAPInterruptedException ex) {
          if (_shutdownCalled) {
            break;
          } else {
            if (debugger.warningEnabled()) {
              debugger.warning("EventService.run() " + "LDAPInterruptedException received:", ex);
            }
          }
        } catch (LDAPException ex) {
          if (_shutdownCalled) {
            break;
          } else {
            int resultCode = ex.getLDAPResultCode();
            if (debugger.warningEnabled()) {
              debugger.warning("EventService.run() LDAPException " + "received:", ex);
            }
            _retryErrorCodes = getPropertyRetryErrorCodes(EVENT_CONNECTION_ERROR_CODES);

            // Catch special error codition in
            // LDAPSearchListener.getResponse
            String msg = ex.getLDAPErrorMessage();
            if ((resultCode == LDAPException.OTHER)
                && (msg != null)
                && msg.equals("Invalid response")) {
              // We should not try to resetError and retry
              processNetworkError(ex);
            } else {
              if (_retryErrorCodes.contains("" + resultCode)) {
                resetErrorSearches(true);
              } else { // Some other network error
                processNetworkError(ex);
              }
            }
          }
        }
      } // end of while loop
    } catch (InterruptedException ex) {
      if (!_shutdownCalled) {
        if (debugger.warningEnabled()) {
          debugger.warning("EventService.run(): Interrupted exception" + " caught.", ex);
        }
      }
    } catch (RuntimeException ex) {
      if (debugger.warningEnabled()) {
        debugger.warning("EventService.run(): Runtime exception " + "caught.", ex);
      }
      // rethrow the Runtime exception to let the container handle the
      // exception.
      throw ex;
    } catch (Exception ex) {
      if (debugger.warningEnabled()) {
        debugger.warning("EventService.run(): Unknown exception " + "caught.", ex);
      }
      // no need to rethrow.
    } catch (Throwable t) {
      // Catching Throwable to prevent the thread from exiting.
      if (debugger.warningEnabled()) {
        debugger.warning(
            "EventService.run(): Unknown exception " + "caught. Sleeping for a while.. ", t);
      }
      // rethrow the Error to let the container handle the error.
      throw new Error(t);
    } finally {
      synchronized (this) {
        if (!_shutdownCalled) {
          // try to restart the monitor thread.
          _monitorThread = null;
          startMonitorThread();
        }
      }
    }
  } // end of thread
Ejemplo n.º 14
0
  /**
   * Determine the listener list based on the diable list property and SMS DataStore notification
   * property in Realm mode
   */
  private static void getListenerList() {
    String list = SystemProperties.get(EVENT_LISTENER_DISABLE_LIST, "");
    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.getListenerList(): " + EVENT_LISTENER_DISABLE_LIST + ": " + list);
    }

    boolean enableDataStoreNotification =
        Boolean.parseBoolean(SystemProperties.get(Constants.SMS_ENABLE_DB_NOTIFICATION));
    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.getListenerList(): "
              + "com.sun.identity.sm.enableDataStoreNotification: "
              + enableDataStoreNotification);
    }

    boolean configTime =
        Boolean.parseBoolean(SystemProperties.get(Constants.SYS_PROPERTY_INSTALL_TIME));
    if (debugger.messageEnabled()) {
      debugger.message(
          "EventService.getListenerList(): "
              + Constants.SYS_PROPERTY_INSTALL_TIME
              + ": "
              + configTime);
    }

    // Copy the default listeners
    String[] tmpListeners = new String[ALL_LISTENERS.length];
    System.arraycopy(ALL_LISTENERS, 0, tmpListeners, 0, ALL_LISTENERS.length);

    // Process the configured disabled list first
    boolean disableACI = false, disableUM = false, disableSM = false;
    if (list.length() != 0) {
      StringTokenizer st = new StringTokenizer(list, ",");
      String listener = "";
      while (st.hasMoreTokens()) {
        listener = st.nextToken().trim();
        if (listener.equalsIgnoreCase("aci")) {
          disableACI = true;
        } else if (listener.equalsIgnoreCase("um")) {
          disableUM = true;
        } else if (listener.equalsIgnoreCase("sm")) {
          disableSM = true;
        } else {
          debugger.error(
              "EventService.getListenerList() - " + "Invalid listener name: " + listener);
        }
      }
    }

    if (!disableUM || !disableACI) {
      // Check if AMSDK is configured
      boolean disableAMSDK = true;
      if (!configTime) {
        try {
          ServiceSchemaManager scm =
              new ServiceSchemaManager(getSSOToken(), IdConstants.REPO_SERVICE, "1.0");
          ServiceSchema idRepoSubSchema = scm.getOrganizationSchema();
          Set idRepoPlugins = idRepoSubSchema.getSubSchemaNames();
          if (idRepoPlugins.contains("amSDK")) {
            disableAMSDK = false;
          }
        } catch (SMSException ex) {
          if (debugger.warningEnabled()) {
            debugger.warning(
                "EventService.getListenerList() - " + "Unable to obtain idrepo service", ex);
          }
        } catch (SSOException ex) {
          // Should not happen, ignore the exception
        }
      }
      if (disableAMSDK) {
        disableUM = true;
        disableACI = true;
        if (debugger.messageEnabled()) {
          debugger.message(
              "EventService.getListener"
                  + "List(): AMSDK is not configured or config time. "
                  + "Disabling UM and ACI event listeners");
        }
      }
    }

    // Verify if SMSnotification should be enabled
    if (configTime || ServiceManager.isRealmEnabled()) {
      disableSM = !enableDataStoreNotification;
      if (debugger.messageEnabled()) {
        debugger.message(
            "EventService.getListenerList(): In realm "
                + "mode or config time, SMS listener is set to datastore "
                + "notification flag: "
                + enableDataStoreNotification);
      }
    }

    // Disable the selected listeners
    if (disableACI) {
      tmpListeners[0] = null;
    }
    if (disableUM) {
      tmpListeners[1] = null;
    }
    if (disableSM) {
      tmpListeners[2] = null;
    }
    listeners = tmpListeners;

    // if all disabled, signal to not start the thread
    if (disableACI && disableUM && disableSM) {
      if (debugger.messageEnabled()) {
        debugger.message(
            "EventService.getListenerList() - "
                + "all listeners are disabled, EventService won't start");
      }
      _allDisabled = true;
    } else {
      _allDisabled = false;
    }
  }
Ejemplo n.º 15
0
  /**
   * This the main method of this servlet which takes in the request opens a URLConnection to the
   * CDCServlet endpoint in the OpenAM, and tunnels the request content to it. It parses the
   * Response received and if the HTTP_STATUS is "HTTP_OK" or "HTTP_MOVED_TEMP" POSTs the received
   * Liberty Authn Response to the goto URL specified in the original request.
   */
  private void sendAuthnRequest(
      HttpServletRequest request, HttpServletResponse response, SSOToken token)
      throws ServletException, IOException {
    SessionID sessid = new SessionID(request);
    URL CDCServletURL = null;
    URL sessionServiceURL = null;
    try {
      sessionServiceURL = Session.getSessionServiceURL(sessid);
    } catch (SessionException se) {
      debug.error(
          "CDCClientServlet.sendAuthnRequest: Cannot locate" + " OpenAM instance to forward to.",
          se);
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    if (sessionServiceURL == null) {
      showError(response, "Cannot locate OpenAM instance to forward to");
    }
    // replace "sessionservice" by cdcservlet in obtained URL
    // we use naming so that we get the URL of the exact server
    // where the session is located and get the right deployment
    // descriptor.
    String sessionServiceURLString = sessionServiceURL.toString();
    int serviceNameIndex =
        sessionServiceURLString.lastIndexOf(
            "/", sessionServiceURLString.length() - 2); // avoiding trailing "/"
    // if any
    StringBuilder buffer = new StringBuilder(150);
    buffer
        .append(sessionServiceURLString.substring(0, serviceNameIndex))
        .append(CDCURI)
        .append(QUESTION_MARK)
        .append(request.getQueryString()); // add query string to
    // CDCServletURL

    CDCServletURL = new URL(buffer.toString());

    // save the go to URL of the agent side to ultimately
    // POST to.
    try {
      HttpURLConnection connection = HttpURLConnectionManager.getConnection(CDCServletURL);
      connection.setRequestMethod("GET");
      connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
      connection.setDoOutput(true);
      connection.setUseCaches(false);
      // replay cookies
      String strCookies = getCookiesFromRequest(request);
      if (strCookies != null) {
        if (debug.messageEnabled()) {
          debug.message("CDCClientServlet.sendAuthnRequest:Setting " + "cookies = " + strCookies);
        }
        connection.setRequestProperty("Cookie", strCookies);
      }
      // dont wish to follow redirect to agent, since
      // the response needs to go via the CDCClientServlet.
      HttpURLConnection.setFollowRedirects(false);

      // Receiving input from CDCServlet on the AM server instance
      if (debug.messageEnabled()) {
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Getting " + "response back from  " + CDCServletURL);
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response " + "Code " + connection.getResponseCode());
        debug.message(
            "CDCClientServlet.sendAuthnRequest:Response "
                + "Message= "
                + connection.getResponseMessage());
      }

      // Check response code
      if ((connection.getResponseCode() == HttpURLConnection.HTTP_OK)
          || (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP)) {
        /**
         * Read the response back from CDCServlet, got a redirect since this response contains the
         * "LARES" ( Liberty authn response, which needs to be posted back to the dest url (agent).
         */
        StringBuilder inBuf = new StringBuilder();
        BufferedReader in =
            new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        int len;
        char[] buf = new char[1024];
        while ((len = in.read(buf, 0, buf.length)) != -1) {
          inBuf.append(buf, 0, len);
        }
        String inString = inBuf.toString();
        if (debug.messageEnabled()) {
          debug.message(
              "CDCClientServlet.sendAuthnRequest:" + "Received response data = " + inString);
        }
        // put the received Liberty Auth Response
        // in the servlet's response.
        sendAuthnResponse(request, response, inString);
      } else {
        debug.error("CDCClientServlet.sendAuthnRequest: Response " + "code NOT OK/MOVED_TEMP ");
        showError(
            response,
            "ERROR: Received HTTP error code "
                + connection.getResponseCode()
                + " from "
                + CDCServletURL);
      }
    } catch (ConnectException ce) {
      // Debug the exception
      if (debug.warningEnabled()) {
        debug.warning(
            "CDCClientServlet.sendAuthnRequest: " + "Connection Exception to " + CDCServletURL, ce);
      }
      showError(
          response, "Could not connect to CDCServlet at " + CDCServletURL + ":" + ce.getMessage());
    }
  }
Ejemplo n.º 16
0
  static {
    bundle = Locale.getInstallResourceBundle("libSOAPBinding");
    faultStringServerError = bundle.getString("ServerError");
    debug = Debug.getInstance("libIDWSF");

    try {
      messageFactory = MessageFactory.newInstance();
    } catch (Exception ex) {
      debug.error("Utils.static: Unable to create SOAP Message Factory", ex);
    }

    String tmpNSPre = SystemPropertiesManager.get(NAMESPACE_PREFIX_MAPPING_LIST_PROP);
    if (tmpNSPre != null && tmpNSPre.length() > 0) {
      StringTokenizer stz = new StringTokenizer(tmpNSPre, "|");
      while (stz.hasMoreTokens()) {
        String token = stz.nextToken().trim();
        int index = token.indexOf('=');
        if (index != -1 && index != 0 && index != token.length() - 1) {
          String prefix = token.substring(0, index);
          String ns = token.substring(index + 1);
          if (debug.messageEnabled()) {
            debug.message("Utils.static: add ns = " + ns + ", prefix = " + prefix);
          }
          nsPrefix.put(ns, prefix);
        } else {
          if (debug.warningEnabled()) {
            debug.warning(
                "Utils.static: Invalid syntax " + "for Namespace Prefix Mapping List: " + token);
          }
        }
      }
    }

    String tmpJaxbPkgs = SystemPropertiesManager.get(JAXB_PACKAGE_LIST_PROP);
    if (tmpJaxbPkgs != null && tmpJaxbPkgs.length() > 0) {
      jaxbPackages = DEFAULT_JAXB_PACKAGES + ":" + tmpJaxbPkgs;
    } else {
      jaxbPackages = DEFAULT_JAXB_PACKAGES;
    }
    if (debug.messageEnabled()) {
      debug.message("Utils.static: jaxbPackages = " + jaxbPackages);
    }

    try {
      jc = JAXBContext.newInstance(jaxbPackages);
    } catch (JAXBException jaxbe) {
      Utils.debug.error("Utils.static:", jaxbe);
    }

    String tmpstr = SystemPropertiesManager.get(STALE_TIME_LIMIT_PROP);
    if (tmpstr != null) {
      try {
        stale_time_limit = Integer.parseInt(tmpstr);
      } catch (Exception ex) {
        if (debug.warningEnabled()) {
          debug.warning(
              "Utils.static: Unable to get stale time " + "limit. Default value will be used");
        }
      }
    }

    tmpstr = SystemPropertiesManager.get(SUPPORTED_ACTORS_PROP);
    if (tmpstr != null) {
      StringTokenizer stz = new StringTokenizer(tmpstr, "|");
      while (stz.hasMoreTokens()) {
        String token = stz.nextToken();
        if (token.length() > 0) {
          supportedActors.add(token);
        }
      }
    }
    tmpstr = SystemPropertiesManager.get(MESSAGE_ID_CACHE_CLEANUP_INTERVAL_PROP);
    if (tmpstr != null) {
      try {
        message_ID_cleanup_interval = Integer.parseInt(tmpstr);
      } catch (Exception ex) {
        if (debug.warningEnabled()) {
          debug.warning(
              "Utils.CleanUpThread.static: Unable to"
                  + " get stale time limit. Default value "
                  + "will be used");
        }
      }
    }
    messageIDMap = new PeriodicCleanUpMap(message_ID_cleanup_interval, stale_time_limit);
    SystemTimerPool.getTimerPool()
        .schedule(
            (TaskRunnable) messageIDMap,
            new Date(((System.currentTimeMillis() + message_ID_cleanup_interval) / 1000) * 1000));
  }