/**
  * TODO: Description.
  *
  * @param service
  * @param config TODO.
  * @throws JsonValueException TODO.
  */
 public Policy(SynchronizationService service, JsonValue config) throws JsonValueException {
   this.service = service;
   situation = config.get("situation").required().asEnum(Situation.class);
   JsonValue action = config.get("action").required();
   if (action.isString()) {
     this.action = action.asEnum(Action.class);
     this.script = null;
     this.scriptScope = null;
   } else {
     this.action = null;
     this.script = Scripts.newInstance("Policy", action);
     if (action.isMap() && action.asMap().size() > 2) {
       // If there is additional attributes then copy them
       scriptScope = action.copy().asMap();
       scriptScope.remove("type");
       scriptScope.remove("source");
       scriptScope.remove("file");
     } else {
       scriptScope = null;
     }
   }
   JsonValue pAction = config.get("postAction");
   if (pAction.isNull()) {
     this.postAction = null;
   } else {
     this.postAction = Scripts.newInstance("PostAction", pAction);
   }
 }
  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));
  }
 /**
  * Loads the configuration properties in the configuration property file associated with the
  * framework installation; these properties are accessible to the framework and to bundles and are
  * intended for configuration purposes. By default, the configuration property file is located in
  * the <tt>conf/</tt> directory and is called " <tt>config.properties</tt>".
  *
  * @return A <tt>Map<String, Object></tt> instance or <tt>null</tt> if there was an error.
  */
 protected Map<String, String> loadConfigProperties(
     JsonValue configuration, URI projectDirectory) {
   JsonValue systemProperties = configuration.get(CONFIG_PROPERTIES_PROP);
   if (systemProperties.isMap()) {
     // Substitute all variables
     systemProperties = systemProperties.copy();
   } else {
     Properties props =
         loadPropertyFile(
             projectDirectory,
             systemProperties
                 .expect(String.class)
                 .defaultTo(CONFIG_PROPERTIES_FILE_VALUE)
                 .asString());
     if (props == null) return new HashMap<String, String>(0);
     // Perform variable substitution on specified properties.
     systemProperties = (new JsonValue(props, null, Arrays.asList(transformer))).copy();
   }
   Map<String, String> config = new HashMap<String, String>(systemProperties.size());
   for (Map.Entry<String, Object> entry : systemProperties.asMap().entrySet()) {
     if (entry.getValue() instanceof String) {
       // Excluce the null and non String values
       config.put(entry.getKey(), (String) entry.getValue());
     }
   }
   return config;
 }
  /*
   Alice has removed Dave's rights to EDIT, so EDIT needs removing from the
   active Dave -> Ed policy, and adding to an inactive policy.
  */
  @Test
  public void shouldRemoveLostRights() throws Exception {
    // Given
    List<Resource> policies = excludePolicies(DAVE, ED);
    policies.add(makePolicy(DAVE, ED, true, VIEW, DELETE, EDIT));

    PolicyGraph graph = makePolicyGraph(policies);
    graph.computeGraph();

    given(resourceSetStore.read(anyString()))
        .willReturn(new ResourceSetDescription(RESOURCE_SET_ID, "RESOURCE_SERVER_ID", ALICE, null));

    given(delegate.updatePolicies(isNull(ServerContext.class), anySet()))
        .willReturn(
            Promises.<List<Resource>, ResourceException>newResultPromise(
                Collections.<Resource>emptyList()));

    given(delegate.createPolicies(isNull(ServerContext.class), anySet()))
        .willReturn(
            Promises.<List<Resource>, ResourceException>newResultPromise(
                Collections.<Resource>emptyList()));

    // When
    Promise<List<List<Resource>>, ResourceException> promise = graph.update(null, delegate);

    // Then
    AssertJPromiseAssert.assertThat(promise).succeeded();
    JsonValue created = policyCreated();
    assertThat(UmaPolicyUtils.getPolicyScopes(created)).containsOnly(EDIT);
    assertThat(created.get("active").asBoolean()).isFalse();
    assertThat(UmaPolicyUtils.getPolicyScopes(policyUpdated())).containsOnly(VIEW, DELETE);
    verifyNoMoreInteractions(delegate);
  }
Exemple #5
0
  /**
   * Creates Organization within OpenAM
   *
   * @param ocm Organization Configuration Manager
   * @param jVal JSONvalue that contains the payload
   * @param realm Name of the realm to be created
   * @throws SMSException
   * @throws Exception
   */
  private void createOrganization(
      OrganizationConfigManager ocm, JsonValue jVal, String realm, String realmPath)
      throws Exception {

    Map defaultValues = null;
    OrganizationConfigManager realmCreatedOcm;
    if (realmPath != null && !realmPath.endsWith("/")) {
      realmPath = realmPath + "/";
    }
    try {
      JsonValue realmDetails = jVal;
      if (jVal != null) {
        defaultValues = createServicesMap(jVal);
      }
      ocm.createSubOrganization(realm, defaultValues);
      // Get the Organization Configuration Manager for the new Realm
      realmCreatedOcm = new OrganizationConfigManager(getSSOToken(), realmPath + realm);
      List newServiceNames = realmDetails.get(SERVICE_NAMES).asList();
      if (newServiceNames != null && !newServiceNames.isEmpty()) {
        // assign services to realm
        assignServices(realmCreatedOcm, newServiceNames);
      }
    } catch (SMSException smse) {
      debug.error("RealmResource.createOrganization()", smse);
      throw smse;
    } catch (Exception e) {
      debug.error("RealmResource.createOrganization()", e);
      throw e;
    }
  }
 /**
  * Loads the properties in the system property file associated with the framework installation
  * into <tt>System.setProperty()</tt>. These properties are not directly used by the framework in
  * anyway. By default, the system property file is located in the <tt>conf/</tt> directory and is
  * called "<tt>system.properties</tt>".
  */
 protected void loadSystemProperties(JsonValue configuration, URI projectDirectory) {
   JsonValue systemProperties = configuration.get(SYSTEM_PROPERTIES_PROP);
   if (systemProperties.isMap()) {
     for (Map.Entry<String, Object> entry : systemProperties.copy().asMap().entrySet()) {
       // The user.dir MUST not be overwritten!!!
       if (entry.getValue() instanceof String && !"user.dir".equals(entry.getKey())) {
         System.setProperty(entry.getKey(), (String) entry.getValue());
       }
     }
   } else {
     Properties props =
         loadPropertyFile(
             projectDirectory,
             systemProperties
                 .expect(String.class)
                 .defaultTo(SYSTEM_PROPERTIES_FILE_VALUE)
                 .asString());
     if (props == null) return;
     // Perform variable substitution on specified properties.
     for (Enumeration e = props.propertyNames(); e.hasMoreElements(); ) {
       String name = (String) e.nextElement();
       if (!"user.dir".equals(name)) {
         Object newValue = ConfigurationUtil.substVars(props.getProperty(name), propertyAccessor);
         if (newValue instanceof String) {
           System.setProperty(name, (String) newValue);
         }
       }
     }
   }
 }
 @Override
 protected Resource convertValue(JsonValue queryResult) throws ParseException {
   return new Resource(
       queryResult.get(UUID_KEY).asString(),
       Integer.toString(queryResult.hashCode()),
       queryResult);
 }
 /**
  * Checks that the JSON callback being converted is of the same type as the CallbackHandler.
  *
  * @param callbackName The required name of the callback.
  * @param jsonCallback The JSON callback object.
  */
 final void validateCallbackType(String callbackName, JsonValue jsonCallback)
     throws RestAuthException {
   String type = jsonCallback.get("type").asString();
   if (!callbackName.equalsIgnoreCase(type)) {
     DEBUG.message(MessageFormat.format("Method called with invalid callback, {0}.", type));
     throw new RestAuthException(
         ResourceException.BAD_REQUEST,
         MessageFormat.format("Invalid Callback, {0}, for handler", type));
   }
 }
 /**
  * Updates the underlying backend policies.
  *
  * <p>NOTE: if the update of the underlying policies fails, the underlying policies may be in an
  * inconsistent state.
  *
  * @param context The request context.
  * @param policies The updated underlying policies to update.
  * @return A promise containing the list of updated underlying policies or a {@code
  *     ResourceException} if the update failed.
  */
 public Promise<List<Resource>, ResourceException> updatePolicies(
     ServerContext context, Set<JsonValue> policies) {
   List<Promise<Resource, ResourceException>> promises =
       new ArrayList<Promise<Resource, ResourceException>>();
   for (JsonValue policy : policies) {
     String policyName = policy.get("name").asString();
     promises.add(
         policyResource.handleUpdate(context, Requests.newUpdateRequest(policyName, policy)));
   }
   return Promises.when(promises);
 }
  /**
   * Expands any interpolation contained within the JsonValue object in-place.
   *
   * @param json JsonValue to parse for macros
   */
  public static void expand(JsonValue json) {
    Iterator<String> iter = json.keys().iterator();
    while (iter.hasNext()) {
      String key = iter.next();

      String expanded = parse(json.get(key));
      if (expanded != null) {
        json.put(key, expanded);
      }
    }
  }
 private static List<Resource> excludePolicies(String owner, String subject) {
   List<Resource> resources = new ArrayList<>(VALID_POLICIES);
   for (Iterator<Resource> i = resources.iterator(); i.hasNext(); ) {
     JsonValue policy = i.next().getContent();
     if (owner.equals(policy.get(PolicyGraph.OWNER_KEY).asString())
         && subject.equals(UmaPolicyUtils.getPolicySubject(policy))) {
       i.remove();
     }
   }
   return resources;
 }
Exemple #12
0
 /**
  * Queries a single link and populates the object with its settings
  *
  * @param The query parameters
  * @throws SynchronizationException if getting and initializing the link details fail
  */
 private void getLink(JsonValue query) throws SynchronizationException {
   JsonValue results =
       linkQuery(
           mapping.getService().getServerContext(),
           mapping.getService().getConnectionFactory(),
           query);
   if (results.size() == 1) {
     fromJsonValue(results.get(0));
   } else if (results.size() > 1) { // shouldn't happen if index is unique
     throw new SynchronizationException("More than one link found");
   }
 }
Exemple #13
0
  /**
   * Creates a Map from JsonValue content
   *
   * @param realmDetails Payload that is from request
   * @return Map of default Services needed to create realm
   * @throws Exception
   */
  private Map createServicesMap(JsonValue realmDetails) throws Exception {
    // Default Attribtes
    final String rstatus = realmDetails.get(IdConstants.ORGANIZATION_STATUS_ATTR).asString();
    // get the realm/DNS Aliases
    final String realmAliases = realmDetails.get(IdConstants.ORGANIZATION_ALIAS_ATTR).asString();
    Map defaultValues = new HashMap(2);
    try {
      Map map = new HashMap(2);
      Set values = new HashSet(2);

      values.add(getStatusAttribute(rstatus));
      map.put(IdConstants.ORGANIZATION_STATUS_ATTR, values);
      if (realmAliases != null && !realmAliases.isEmpty()) {
        Set values1 = new HashSet(2);
        values1.add(realmAliases);
        map.put(IdConstants.ORGANIZATION_ALIAS_ATTR, values1);
      }
      defaultValues.put(IdConstants.REPO_SERVICE, map);
    } catch (Exception e) {
      throw e;
    }
    return defaultValues;
  }
  private String getTicketId(JsonValue requestBody) throws BadRequestException {
    final JsonValue ticket = requestBody.get("ticket");

    String ticketId = null;

    try {
      ticketId = ticket.asString();
    } catch (Exception e) {
      throw new BadRequestException(UNABLE_TO_RETRIEVE_TICKET_MESSAGE);
    }

    if (ticketId == null) {
      throw new BadRequestException(UNABLE_TO_RETRIEVE_TICKET_MESSAGE);
    }

    return ticketId;
  }
Exemple #15
0
 /**
  * TODO: Description.
  *
  * @param value TODO.
  * @throws org.forgerock.json.fluent.JsonValueException
  */
 private void fromJsonValue(JsonValue jv) throws JsonValueException {
   _id = jv.get("_id").required().asString();
   _rev = jv.get("_rev").asString(); // optional
   if (mapping.getLinkType().useReverse()) {
     sourceId = jv.get("secondId").required().asString();
     targetId = jv.get("firstId").required().asString();
   } else {
     sourceId = jv.get("firstId").required().asString();
     targetId = jv.get("secondId").required().asString();
   }
   linkQualifier = jv.get("linkQualifier").asString();
   sourceId = mapping.getLinkType().normalizeSourceId(sourceId);
   targetId = mapping.getLinkType().normalizeTargetId(targetId);
   initialized = true;
 }
 /**
  * Loads the boot properties in the configuration property file associated with the framework
  * installation; these properties are accessible to the framework and to bundles and are intended
  * for configuration purposes. By default, the configuration property file is located in the
  * <tt>conf/</tt> directory and is called " <tt>config.properties</tt>".
  *
  * @return A <tt>Map<String, Object></tt> instance or <tt>null</tt> if there was an error.
  */
 protected Map<String, Object> loadBootProperties(JsonValue configuration, URI projectDirectory) {
   JsonValue bootProperties = configuration.get(BOOT_PROPERTIES_PROP);
   if (bootProperties.isMap()) {
     // Substitute all variables
     return bootProperties.copy().asMap();
   } else {
     Properties props =
         loadPropertyFile(
             projectDirectory,
             bootProperties.expect(String.class).defaultTo(BOOT_PROPERTIES_FILE_VALUE).asString());
     if (props == null) return new HashMap<String, Object>(0);
     // Perform variable substitution on specified properties.
     return (new JsonValue(props, null, Arrays.asList(transformer)))
         .expect(Map.class)
         .copy()
         .asMap();
   }
 }
Exemple #17
0
    void setConfiguredQueries(Map<String, String> replacements, JsonValue queriesConfig) {
      configured.clear();
      for (String queryName : queriesConfig.keys()) {
        String rawQuery = queriesConfig.get(queryName).required().asString();

        TokenHandler tokenHandler = new TokenHandler();
        // Replace the table name tokens.
        String tempQueryString = tokenHandler.replaceSomeTokens(rawQuery, replacements);

        // Convert to ? for prepared statement, populate token replacement info
        List<String> tokenNames = tokenHandler.extractTokens(tempQueryString);
        String queryString = tokenHandler.replaceTokens(tempQueryString, "?", PREFIX_LIST);

        QueryInfo queryInfo = new QueryInfo(queryString, tokenNames);
        configured.put(queryName, queryInfo);
        logger.info(
            "Configured query converted to JDBC query {} and tokens {}", queryString, tokenNames);
      }
    }
  /** {@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;
  }
 /**
  * Returns a JSON object containing only the specified fields from the provided JSON value. If the
  * list of fields is empty then the value is returned unchanged.
  *
  * <p><b>NOTE:</b> this method only performs a shallow copy of extracted fields, so changes to the
  * filtered JSON value may impact the original JSON value, and vice-versa.
  *
  * @param resource The JSON value whose fields are to be filtered.
  * @param fields The list of fields to be extracted.
  * @return The filtered JSON value.
  */
 public static JsonValue filterResource(
     final JsonValue resource, final Collection<JsonPointer> fields) {
   if (fields.isEmpty() || resource.isNull() || resource.size() == 0) {
     return resource;
   } else {
     final Map<String, Object> filtered = new LinkedHashMap<String, Object>(fields.size());
     for (JsonPointer field : fields) {
       if (field.isEmpty()) {
         // Special case - copy resource fields (assumes Map).
         filtered.putAll(resource.asMap());
       } else {
         // FIXME: what should we do if the field refers to an array element?
         final JsonValue value = resource.get(field);
         if (value != null) {
           final String key = field.leaf();
           filtered.put(key, value.getObject());
         }
       }
     }
     return new JsonValue(filtered);
   }
 }
  /**
   * Stores the <code>Dictionary</code> under the given <code>pid</code>.
   *
   * @param pid The identifier of the dictionary.
   * @param properties The <code>Dictionary</code> to store.
   * @throws IOException If an error occurrs storing the dictionary. If this exception is thrown, it
   *     is expected, that {@link #exists(String) exists(pid} returns <code>false</code>.
   */
  public void store(String pid, Dictionary properties) throws IOException {
    logger.debug("Store call for {} {}", pid, properties);

    // Store config handling settings in memory
    if (pid.startsWith("org.apache.felix.fileinstall")) {
      tempStore.put(pid, properties);
      return;
    }

    try {
      if (isReady(0) && requireRepository) {
        String id = pidToId(pid);

        Map<String, Object> obj = dictToMap(properties);
        JsonValue content = new JsonValue(obj);
        String configResourceId =
            ConfigBootstrapHelper.getId(
                content.get(ConfigBootstrapHelper.CONFIG_ALIAS).asString(),
                content.get(ConfigBootstrapHelper.SERVICE_PID).asString(),
                content.get(ConfigBootstrapHelper.SERVICE_FACTORY_PID).asString());
        String configString = (String) obj.get(JSONEnhancedConfig.JSON_CONFIG_PROPERTY);
        Map<Object, Object> configMap = deserializeConfig(configString);
        if (configMap != null) {
          configMap.put("_id", configResourceId);
        }
        obj.put(JSONEnhancedConfig.JSON_CONFIG_PROPERTY, configMap);

        Map<String, Object> existing = null;
        try {
          ReadRequest readRequest = Requests.newReadRequest(id);
          existing = repo.read(readRequest).getContent().asMap();
        } catch (NotFoundException ex) {
          // Just detect that it doesn't exist
        }
        if (existing != null) {
          String rev = (String) existing.get("_rev");

          existing.remove("_rev");
          existing.remove("_id");
          obj.remove("_rev"); // beware, this means _id and _rev should not be in config file
          obj.remove("_id"); // beware, this means _id and _rev should not be in config file
          obj.remove(RepoPersistenceManager.BUNDLE_LOCATION);
          obj.remove(RepoPersistenceManager.FELIX_FILEINSTALL_FILENAME);
          if (!existing.equals(obj)) {
            logger.trace("Not matching {} {}", existing, obj);
            boolean retry;
            do {
              retry = false;
              try {
                UpdateRequest r = Requests.newUpdateRequest(id, new JsonValue(obj));
                r.setRevision(rev);
                repo.update(r);
              } catch (PreconditionFailedException ex) {
                logger.debug("Concurrent change during update, retrying {} {}", pid, rev);
                ReadRequest readRequest = Requests.newReadRequest(id);
                existing = repo.read(readRequest).getContent().asMap();
                retry = true;
              }
            } while (retry);
            logger.debug("Updated existing config {} {} {}", new Object[] {pid, rev, obj});
          } else {
            logger.debug(
                "Existing config same as store request, ignoring {} {} {}",
                new Object[] {pid, rev, obj});
          }
        } else {
          logger.trace("Creating: {} {} ", id, obj);
          // This may create a new (empty) configuration, which felix marks with
          // _felix___cm__newConfiguration=true
          String newResourceId = id.substring(CONFIG_CONTEXT_PREFIX.length());
          CreateRequest createRequest =
              Requests.newCreateRequest(CONFIG_CONTEXT_PREFIX, new JsonValue(obj));
          createRequest.setNewResourceId(newResourceId);
          obj = repo.create(createRequest).getContent().asMap();
          logger.debug("Stored new config in repository {} {}", pid, obj);
        }
      } else {
        tempStore.put(pid, properties);
        logger.debug("Stored in memory {} {}", pid, properties);
      }
    } catch (ResourceException ex) {
      throw new IOException("Failed to store configuration in repository: " + ex.getMessage(), ex);
    }
  }
 /**
  * Checks to see if the given JSON object has the specified attribute name.
  *
  * @param jsonObject The JSON object.
  * @param attributeName The attribute name to check the presence of.
  * @return If the JSON object contains the attribute name.
  */
 boolean isJsonAttributePresent(JsonValue jsonObject, String attributeName) {
   if (jsonObject.get(attributeName).isNull()) {
     return false;
   }
   return true;
 }
Exemple #22
0
  /** {@inheritDoc} */
  @Override
  public void updateInstance(
      final ServerContext context,
      final String resourceId,
      final UpdateRequest request,
      final ResultHandler<Resource> handler) {

    RealmContext realmContext = context.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();

    final JsonValue realmDetails = request.getContent();
    Resource resource;
    String realm = null;
    OrganizationConfigManager ocm;
    OrganizationConfigManager realmCreatedOcm;

    String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);

    try {

      hasPermission(context);
      realm = checkForTopLevelRealm(resourceId);
      if (realm != null && !realm.startsWith("/")) {
        realm = "/" + realm;
      }
      if (!realmPath.equalsIgnoreCase("/")) {
        realm = realmPath + realm;
      }
      // The initial attempt to UPDATE a realm,
      // if the realm does not exist it must be created
      ocm = new OrganizationConfigManager(getSSOToken(), realm);
      List newServiceNames;
      // update ID_REPO attributes
      updateConfiguredServices(ocm, createServicesMap(realmDetails));
      newServiceNames = realmDetails.get(SERVICE_NAMES).asList();
      if (newServiceNames == null || newServiceNames.isEmpty()) {
        debug.error("RealmResource.updateInstance() : No Services defined.");
      } else {
        assignServices(ocm, newServiceNames); // assign services to realm
      }
      // READ THE REALM
      realmCreatedOcm = new OrganizationConfigManager(getSSOToken(), realm);

      debug.message(
          "RealmResource.updateInstance :: UPDATE of realm "
              + realm
              + " performed by "
              + principalName);

      // create a resource for handler to return
      resource =
          new Resource(
              realm,
              String.valueOf(System.currentTimeMillis()),
              createJsonMessage("realmUpdated", realmCreatedOcm.getOrganizationName()));
      handler.handleResult(resource);
    } catch (SMSException e) {
      try {
        configureErrorMessage(e);
      } catch (NotFoundException nfe) {
        if (debug.errorEnabled()) {
          debug.error(
              "RealmResource.updateInstance()"
                  + "Cannot find "
                  + resourceId
                  + ":"
                  + e
                  + "\n"
                  + "CREATING "
                  + resourceId);
        }
        // Realm was NOT found, therefore create the realm
        try {
          String parentRealm = RealmUtils.getParentRealm(realm);
          String childRealm = RealmUtils.getChildRealm(realm);
          ocm = new OrganizationConfigManager(getSSOToken(), parentRealm);
          // create the realm
          createOrganization(ocm, realmDetails, childRealm, realmPath);

          // read the realm to make sure that it has been created...
          realmCreatedOcm = new OrganizationConfigManager(getSSOToken(), realm);

          if (debug.messageEnabled()) {
            debug.message(
                "RealmResource.updateInstance :: UPDATE of realm "
                    + realm
                    + " performed by "
                    + principalName);
          }

          resource =
              new Resource(
                  childRealm,
                  String.valueOf(System.currentTimeMillis()),
                  createJsonMessage("realmCreated", realmCreatedOcm.getOrganizationName()));
          if (debug.messageEnabled()) {
            debug.message("RealmResource :: UPDATE : Updated resource with ID, " + resourceId);
          }
          handler.handleResult(resource);
        } catch (SMSException smse) {

          debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, smse);

          try {
            configureErrorMessage(smse);
          } catch (NotFoundException nf) {
            debug.error("RealmResource.updateInstance() : Cannot find " + resourceId, nf);
            handler.handleError(nf);
          } catch (ForbiddenException fe) {
            // User does not have authorization
            debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, fe);
            handler.handleError(fe);
          } catch (PermanentException pe) {
            debug.error("RealmResource.updateInstance() Cannot UPDATE " + resourceId, pe);
            // Cannot recover from this exception
            handler.handleError(pe);
          } catch (ConflictException ce) {
            debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ce);
            handler.handleError(ce);
          } catch (BadRequestException be) {
            debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, be);
            handler.handleError(be);
          }
        } catch (Exception ex) {
          debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ex);
          handler.handleError(new NotFoundException("Cannot update realm.", ex));
        }

      } catch (ForbiddenException fe) {
        // User does not have authorization
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, fe);
        handler.handleError(fe);
      } catch (PermanentException pe) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, pe);
        // Cannot recover from this exception
        handler.handleError(pe);
      } catch (ConflictException ce) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ce);
        handler.handleError(ce);
      } catch (BadRequestException be) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, be);
        handler.handleError(be);
      } catch (Exception ex) {
        debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ex);
        handler.handleError(new NotFoundException("Cannot update realm.", ex));
      }
    } catch (SSOException sso) {
      debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, sso);
      handler.handleError(new PermanentException(401, "Access Denied", null));
    } catch (ForbiddenException fe) {
      debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, fe);
      handler.handleError(fe);
    } catch (PermanentException pe) {
      debug.error("RealmResource.Instance() : Cannot UPDATE " + resourceId, pe);
      // Cannot recover from this exception
      handler.handleError(pe);
    } catch (Exception ex) {
      debug.error("RealmResource.updateInstance() : Cannot UPDATE " + resourceId, ex);
      handler.handleError(new NotFoundException("Cannot update realm.", ex));
    }
  }
  protected List<BundleHandler> listBundleHandlers(BundleContext context)
      throws MalformedURLException {
    JsonValue bundle = getLauncherConfiguration().get("bundle");
    BundleHandlerBuilder defaultBuilder = BundleHandlerBuilder.newBuilder(bundle.get("default"));

    List<BundleHandler> result = new ArrayList<BundleHandler>();

    URI installDirectory = getInstallURI();

    for (JsonValue container : bundle.get("containers")) {
      BundleHandlerBuilder innerBuilder =
          BundleHandlerBuilder.newBuilder(container, defaultBuilder);

      String location = container.get("location").required().asString();
      if (location.toLowerCase().endsWith(".zip")) {
        File inputFile = getFileForPath(location, installDirectory);
        for (URL url :
            ConfigurationUtil.getZipFileListing(
                inputFile.toURI().toURL(),
                container.get("includes").asList(String.class),
                container.get("excludes").asList(String.class))) {
          result.add(innerBuilder.build(url));
        }

      } else if (location.toLowerCase().endsWith(".jar")) {
        File inputFile = getFileForPath(location, installDirectory);
        result.add(innerBuilder.build(inputFile.toURI().toURL()));
      } else {
        DirectoryScanner scanner = new DirectoryScanner();
        scanner.setBasedir(getFileForPath(location, installDirectory));
        if (container.isDefined("includes")) {
          List<String> includes = container.get("includes").asList(String.class);
          scanner.setIncludes(includes.toArray(new String[includes.size()]));
        }
        if (container.isDefined("excludes")) {
          List<String> includes = container.get("excludes").asList(String.class);
          scanner.setExcludes(includes.toArray(new String[includes.size()]));
        }
        scanner.scan();

        for (String bundleLocation : scanner.getIncludedFiles()) {
          BundleHandler newHandler =
              innerBuilder.build(
                  scanner
                      .getBasedir()
                      .toURI()
                      .resolve(bundleLocation.replaceAll("\\\\", "/"))
                      .toURL());
          for (BundleHandler handler : result) {
            if (newHandler.getBundleUrl().equals(handler.getBundleUrl())) {
              if (newHandler.getActions().equals(handler.getActions())
                  && newHandler.getStartLevel() == newHandler.getStartLevel()) {
                // Do not duplicate
                newHandler = null;
                break;
              } else {
                StringBuilder sb = new StringBuilder("Controversial provisioning between ");
                sb.append(handler).append(" and ").append(newHandler);
                throw new IllegalArgumentException(sb.toString());
              }
            }
          }
          if (null != newHandler) {
            result.add(newHandler);
          }
        }
      }
    }
    return result;
  }
Exemple #24
0
  /** {@inheritDoc} */
  @Override
  public void createInstance(
      final ServerContext context,
      final CreateRequest request,
      final ResultHandler<Resource> handler) {

    RealmContext realmContext = context.asContext(RealmContext.class);
    String realmPath = realmContext.getResolvedRealm();

    Resource resource;
    String parentRealm;
    String childRealm;
    String realm = null;

    try {
      hasPermission(context);
      final JsonValue jVal = request.getContent();
      // get the realm
      realm = jVal.get("realm").asString();
      realm = checkForTopLevelRealm(realm);
      if (realm == null || realm.isEmpty()) {
        throw new BadRequestException("No realm name provided.");
      } else if (!realm.startsWith("/")) {
        realm = "/" + realm;
      }
      if (!realmPath.equalsIgnoreCase("/")) {
        // build realm to comply with format if not top level
        realm = realmPath + realm;
      }

      parentRealm = RealmUtils.getParentRealm(realm);
      childRealm = RealmUtils.getChildRealm(realm);

      OrganizationConfigManager ocm = new OrganizationConfigManager(getSSOToken(), parentRealm);

      Map defaultValues = createServicesMap(jVal);
      ocm.createSubOrganization(childRealm, defaultValues);
      String principalName = PrincipalRestUtils.getPrincipalNameFromServerContext(context);
      debug.message(
          "RealmResource.createInstance :: CREATE of realm "
              + childRealm
              + " in realm "
              + parentRealm
              + " performed by "
              + principalName);

      // create a resource for handler to return
      OrganizationConfigManager realmCreated = new OrganizationConfigManager(getSSOToken(), realm);
      resource =
          new Resource(
              childRealm,
              String.valueOf(System.currentTimeMillis()),
              createJsonMessage("realmCreated", realmCreated.getOrganizationName()));
      handler.handleResult(resource);

    } catch (SMSException smse) {

      debug.error("RealmResource.createInstance() : Cannot find " + realm, smse);

      try {
        configureErrorMessage(smse);
      } catch (NotFoundException nf) {
        debug.error("RealmResource.createInstance() : Cannot find " + realm, nf);
        handler.handleError(nf);
      } catch (ForbiddenException fe) {
        // User does not have authorization
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, fe);
        handler.handleError(fe);
      } catch (PermanentException pe) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, pe);
        // Cannot recover from this exception
        handler.handleError(pe);
      } catch (ConflictException ce) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, ce);
        handler.handleError(ce);
      } catch (BadRequestException be) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, be);
        handler.handleError(be);
      } catch (Exception e) {
        debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, e);
        handler.handleError(new BadRequestException(e.getMessage(), e));
      }
    } catch (SSOException sso) {
      debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, sso);
      handler.handleError(new PermanentException(401, "Access Denied", null));
    } catch (ForbiddenException fe) {
      debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, fe);
      handler.handleError(fe);
    } catch (BadRequestException be) {
      debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, be);
      handler.handleError(be);
    } catch (PermanentException pe) {
      debug.error("RealmResource.createInstance() : Cannot CREATE " + realm, pe);
      // Cannot recover from this exception
      handler.handleError(pe);
    } catch (Exception e) {
      debug.error("RealmResource.createInstance()" + realm + ":" + e);
      handler.handleError(new BadRequestException(e.getMessage(), e));
    }
  }