/** * 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); }
/** * Start the string parsing. If base is not a string, will return null. * * @param base base JsonValue object to begin parsing from * @return a string with any interpolation expanded or null if base is not a string */ private static String parse(JsonValue base) { if (!base.isString()) { return null; } return buildString(base.asString()); }
@Test public void shouldGetWithSSL() throws ResourceException { // Given setSslConfiguration(); final String uri = "URI"; final Map<String, String> queryParameters = new HashMap<String, String>(); final Map<String, String> headers = new HashMap<String, String>(); final Context context = mock(Context.class); final ConcurrentHashMap<String, Object> requestAttributes = new ConcurrentHashMap<String, Object>(); final JSONObject restResponse = mock(JSONObject.class); given(resource.getContext()).willReturn(context); given(context.getAttributes()).willReturn(requestAttributes); given(resource.get(JSONObject.class)).willReturn(restResponse); given(restResponse.toString()).willReturn("{}"); // When final JsonValue response = restClient.get(uri, queryParameters, headers); // Then verify(resource, never()).addQueryParameter(anyString(), anyString()); verify(requestHeaders, never()).set(anyString(), anyString()); verify(resource).getContext(); assertTrue(requestAttributes.containsKey("sslContextFactory")); assertEquals(response.size(), 0); }
/** * Queries all the links for a given mapping, indexed by the source identifier * * <p>This method expects a {@code "links-for-linkType"} defined with a parameter of {@code * "linkType"}. * * @param mapping the mapping to look up the links for * @throws SynchronizationException if the query could not be performed. * @return the mapping from source identifier to the link object for it */ public static Map<String, Link> getLinksForMapping(ObjectMapping mapping, String linkQualifier) throws SynchronizationException { Map<String, Link> sourceIdToLink = new ConcurrentHashMap<String, Link>(); if (mapping != null) { JsonValue query = new JsonValue(new HashMap<String, Object>()); query.put( PARAM_QUERY_FILTER, QueryFilter.and( Arrays.asList( QueryFilter.equalTo("/linkType", mapping.getLinkType().getName()), QueryFilter.equalTo("/linkQualifier", linkQualifier))) .toString()); JsonValue queryResults = linkQuery( mapping.getService().getServerContext(), mapping.getService().getConnectionFactory(), query); for (JsonValue entry : queryResults) { Link link = new Link(mapping); link.fromJsonValue(entry); sourceIdToLink.put(link.sourceId, link); } } return sourceIdToLink; }
/* 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); }
/** * 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; } }
/** {@inheritDoc} */ @Override public String toString() { final JsonValue wrapper = new JsonValue(new LinkedHashMap<String, Object>(3)); wrapper.add("id", id); wrapper.add("rev", revision); wrapper.add("content", content); return wrapper.toString(); }
/** * Returns a JsonValue containing appropriate identity details * * @param message Description of result * @return The JsonValue Object */ private JsonValue createJsonMessage(String key, Object message) { JsonValue result = new JsonValue(new LinkedHashMap<String, Object>(1)); try { result.put(key, message); return result; } catch (final Exception e) { throw new JsonValueException(result); } }
/** * 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); } } }
/** * 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); }
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; }
/** * 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"); } }
/** * TODO: Description. * * @param source * @param target * @param syncOperation the parent {@link ObjectMapping.SyncOperation} instance * @return TODO. * @throws SynchronizationException TODO. */ public Action getAction( LazyObjectAccessor source, LazyObjectAccessor target, final ObjectMapping.SyncOperation syncOperation) throws SynchronizationException { Action result = null; if (action != null) { // static action specified result = action; } else if (script != null) { // action is dynamically determine Map<String, Object> scope = new HashMap<String, Object>(); if (null != scriptScope) { // Make a thread safe copy and put the variables into the scope for (Map.Entry<String, Object> entry : Utils.deepCopy(scriptScope).entrySet()) { if (scope.containsKey(entry.getKey())) { continue; } scope.put(entry.getKey(), entry.getValue()); } } Map<String, Object> recon = new HashMap<String, Object>(); scope.put("recon", recon); JsonValue actionParam = null; if (syncOperation instanceof ObjectMapping.TargetSyncOperation) { actionParam = ((ObjectMapping.TargetSyncOperation) syncOperation).toJsonValue(); } else if (syncOperation instanceof ObjectMapping.SourceSyncOperation) { actionParam = ((ObjectMapping.SourceSyncOperation) syncOperation).toJsonValue(); } if (null != actionParam) { // FIXME Decide if leading underscore should be used here or not actionParam.put("_" + ActionRequest.FIELD_ACTION, "performAction"); recon.put("actionParam", actionParam.getObject()); } scope.put("sourceAction", (syncOperation instanceof ObjectMapping.SourceSyncOperation)); if (source != null) { scope.put("source", source.asMap()); } if (target != null) { scope.put("target", target.asMap()); } try { result = Enum.valueOf(Action.class, script.exec(scope).toString()); } catch (NullPointerException npe) { throw new SynchronizationException("action script returned null value"); } catch (IllegalArgumentException iae) { throw new SynchronizationException("action script returned invalid action"); } catch (ScriptException se) { LOGGER.debug("action script encountered exception", se); throw new SynchronizationException(se); } } return result; }
/** * Returns a JsonValue containing Service Names and Values * * @param ocm The organization configuration manager * @param serviceNames Names of the services available to the organization * @return The JsonValue Object containing attributes assigned to the services */ private JsonValue serviceNamesToJSON(OrganizationConfigManager ocm, Set serviceNames) throws SMSException { JsonValue realmServices = new JsonValue(new LinkedHashMap<String, Object>(1)); try { for (Object service : serviceNames) { String tmp = (String) service; Object holdAttrForService = ocm.getAttributes(tmp); realmServices.add(tmp, holdAttrForService); } } catch (SMSException e) { debug.error("RealmResource.serviceNamesToJSON :: " + e); throw e; } return realmServices; }
/** * Queries the links for a match on the second system (links can be bi-directional) * * <p>This method expects a {@code "links-for-targetId"} defined with a parameter of {@code * "targetId"}. * * @param targetId TODO. * @throws SynchronizationException TODO. */ void getLinkFromSecond(String id) throws SynchronizationException { clear(); if (id != null) { JsonValue query = new JsonValue(new HashMap<String, Object>()); query.put( PARAM_QUERY_FILTER, QueryFilter.and( Arrays.asList( QueryFilter.equalTo("/linkType", mapping.getLinkType().getName()), QueryFilter.equalTo("/linkQualifier", linkQualifier), QueryFilter.equalTo("/secondId", id))) .toString()); getLink(query); } }
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 static Resource makePolicy( String owner, String subject, boolean active, String... scopes) { String policyId = owner + "-" + subject + "-" + active; JsonValue policy = json( object( field("_id", policyId), field(PolicyGraph.OWNER_KEY, owner), field(SUBJECT_KEY, object(field(BACKEND_POLICY_SUBJECT_CLAIM_VALUE_KEY, subject))), field(PolicyGraph.ACTIVE_KEY, active))); for (String scope : scopes) { policy.putPermissive(new JsonPointer(BACKEND_POLICY_ACTION_VALUES_KEY + "/" + scope), true); } return new Resource(policyId, String.valueOf(policyId.hashCode()), policy); }
@Override @SuppressWarnings("unchecked") public Object get(String name, Scriptable start) { if (PatchRequest.FIELD_PATCH_OPERATIONS.equals(name)) { final JsonValue value = new JsonValue(new ArrayList<Object>()); for (final PatchOperation operation : request.getPatchOperations()) { value.add(operation.toJsonValue().getObject()); } return Converter.wrap(parameter, value, start, false); } else if (PatchRequest.FIELD_REVISION.equals(name)) { return Converter.wrap(parameter, request.getRevision(), start, false); } else { return super.get(name, start); } }
public JsonValue getLauncherConfiguration() { if (null == launcherConfiguration) { launcherConfiguration = new JsonValue(new HashMap<String, Object>()); launcherConfiguration.getTransformers().add(transformer); } return launcherConfiguration; }
private Map<String, Object> toMap(JsonRepresentation entity) throws BadRequestException { if (entity == null) { return Collections.emptyMap(); } try { final String jsonString = entity.getJsonObject().toString(); if (StringUtils.isNotEmpty(jsonString)) { JsonValue jsonContent = JsonValueBuilder.toJsonValue(jsonString); return jsonContent.asMap(Object.class); } return Collections.emptyMap(); } catch (JSONException e) { throw new BadRequestException(e.getMessage()); } }
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; }
@Test public void testResource() throws Exception { ScriptName scriptName = new ScriptName("resource", getLanguageName()); ScriptEntry scriptEntry = getScriptRegistry().takeScript(scriptName); Assert.assertNotNull(scriptEntry); Script script = scriptEntry.getScript(new RootContext()); // Set RequestLevel Scope script.put("ketto", 2); script.putSafe("callback", mock(Function.class)); JsonValue createContent = new JsonValue(new LinkedHashMap<String, Object>()); createContent.put("externalId", "701984"); createContent.put("userName", "*****@*****.**"); createContent.put( "assignedDashboard", Arrays.asList("Salesforce", "Google", "ConstantContact")); createContent.put("displayName", "Babs Jensen"); createContent.put("nickName", "Babs"); JsonValue updateContent = createContent.copy(); updateContent.put("_id", UUID.randomUUID().toString()); updateContent.put("profileUrl", "https://login.example.com/bjensen"); final Context context = new ApiInfoContext( new SecurityContext(new RootContext(), "*****@*****.**", null), "", ""); script.put("context", context); CreateRequest createRequest = Requests.newCreateRequest("/Users", "701984", createContent); script.put("createRequest", createRequest); ReadRequest readRequest = Requests.newReadRequest("/Users/701984"); script.put("readRequest", readRequest); UpdateRequest updateRequest = Requests.newUpdateRequest("/Users/701984", updateContent); script.put("updateRequest", updateRequest); PatchRequest patchRequest = Requests.newPatchRequest("/Users/701984", PatchOperation.replace("userName", "ddoe")); script.put("patchRequest", patchRequest); QueryRequest queryRequest = Requests.newQueryRequest("/Users/"); script.put("queryRequest", queryRequest); DeleteRequest deleteRequest = Requests.newDeleteRequest("/Users/701984"); script.put("deleteRequest", deleteRequest); ActionRequest actionRequest = Requests.newActionRequest("/Users", "clear"); script.put("actionRequest", actionRequest); script.eval(); }
/** * 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; }
/** * 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(); } }
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); } }
/** * 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)); } }
/** * Returns the exception in a JSON object structure, suitable for inclusion in the entity of an * HTTP error response. The JSON representation looks like this: * * <pre> * { * "code" : 404, * "reason" : "...", // optional * "message" : "...", // required * "detail" : { ... } // optional * "cause" : { ... } // optional iff includeCause is set to true * } * </pre> * * @return The exception in a JSON object structure, suitable for inclusion in the entity of an * HTTP error response. */ public final JsonValue toJsonValue() { final Map<String, Object> result = new LinkedHashMap<String, Object>(4); result.put(FIELD_CODE, code); // required if (reason != null) { // optional result.put(FIELD_REASON, reason); } final String message = getMessage(); if (message != null) { // should always be present result.put(FIELD_MESSAGE, message); } if (!detail.isNull()) { result.put(FIELD_DETAIL, detail.getObject()); } if (includeCause && getCause() != null && getCause().getMessage() != null) { final Map<String, Object> cause = new LinkedHashMap<String, Object>(2); cause.put("message", getCause().getMessage()); result.put(FIELD_CAUSE, cause); } return new JsonValue(result); }
/** {@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; }
@Test public void shouldGetWithEmptyQueryParameters() throws ResourceException { // Given final String uri = "URI"; final Map<String, String> queryParameters = new HashMap<String, String>(); final Map<String, String> headers = new HashMap<String, String>(); final JSONObject restResponse = mock(JSONObject.class); given(resource.get(JSONObject.class)).willReturn(restResponse); given(restResponse.toString()).willReturn("{}"); // When final JsonValue response = restClient.get(uri, queryParameters, headers); // Then verify(resource, never()).addQueryParameter(anyString(), anyString()); verify(requestHeaders, never()).set(anyString(), anyString()); verify(resource, never()).getContext(); assertEquals(response.size(), 0); }