use of org.apache.commons.lang3.StringUtils.isBlank in project nifi-registry by apache.
the class LdapUserGroupProvider method load.
/**
* Reloads the tenants.
*/
private void load(final ContextSource contextSource) {
// create the ldapTemplate based on the context source. use a single source context to use the same connection
// to support paging when configured
final SingleContextSource singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext());
final LdapTemplate ldapTemplate = new LdapTemplate(singleContextSource);
try {
final List<User> userList = new ArrayList<>();
final List<Group> groupList = new ArrayList<>();
// group dn -> user identifiers lookup
final Map<String, Set<String>> groupToUserIdentifierMappings = new HashMap<>();
// user dn -> user lookup
final Map<String, User> userLookup = new HashMap<>();
if (performUserSearch) {
// search controls
final SearchControls userControls = new SearchControls();
userControls.setSearchScope(userSearchScope.ordinal());
// consider paging support for users
final DirContextProcessor userProcessor;
if (pageSize == null) {
userProcessor = new NullDirContextProcessor();
} else {
userProcessor = new PagedResultsDirContextProcessor(pageSize);
}
// looking for objects matching the user object class
final AndFilter userFilter = new AndFilter();
userFilter.and(new EqualsFilter("objectClass", userObjectClass));
// if a filter has been provided by the user, we add it to the filter
if (StringUtils.isNotBlank(userSearchFilter)) {
userFilter.and(new HardcodedFilter(userSearchFilter));
}
do {
userList.addAll(ldapTemplate.search(userSearchBase, userFilter.encode(), userControls, new AbstractContextMapper<User>() {
@Override
protected User doMapFromContext(DirContextOperations ctx) {
// get the user identity
final String identity = getUserIdentity(ctx);
// build the user
final User user = new User.Builder().identifierGenerateFromSeed(identity).identity(identity).build();
// store the user for group member later
userLookup.put(getReferencedUserValue(ctx), user);
if (StringUtils.isNotBlank(userGroupNameAttribute)) {
final Attribute attributeGroups = ctx.getAttributes().get(userGroupNameAttribute);
if (attributeGroups == null) {
logger.warn("User group name attribute [" + userGroupNameAttribute + "] does not exist. Ignoring group membership.");
} else {
try {
final NamingEnumeration<String> groupValues = (NamingEnumeration<String>) attributeGroups.getAll();
while (groupValues.hasMoreElements()) {
// store the group -> user identifier mapping
groupToUserIdentifierMappings.computeIfAbsent(groupValues.next(), g -> new HashSet<>()).add(user.getIdentifier());
}
} catch (NamingException e) {
throw new AuthorizationAccessException("Error while retrieving user group name attribute [" + userIdentityAttribute + "].");
}
}
}
return user;
}
}, userProcessor));
} while (hasMorePages(userProcessor));
}
if (performGroupSearch) {
final SearchControls groupControls = new SearchControls();
groupControls.setSearchScope(groupSearchScope.ordinal());
// consider paging support for groups
final DirContextProcessor groupProcessor;
if (pageSize == null) {
groupProcessor = new NullDirContextProcessor();
} else {
groupProcessor = new PagedResultsDirContextProcessor(pageSize);
}
// looking for objects matching the group object class
AndFilter groupFilter = new AndFilter();
groupFilter.and(new EqualsFilter("objectClass", groupObjectClass));
// if a filter has been provided by the user, we add it to the filter
if (StringUtils.isNotBlank(groupSearchFilter)) {
groupFilter.and(new HardcodedFilter(groupSearchFilter));
}
do {
groupList.addAll(ldapTemplate.search(groupSearchBase, groupFilter.encode(), groupControls, new AbstractContextMapper<Group>() {
@Override
protected Group doMapFromContext(DirContextOperations ctx) {
final String dn = ctx.getDn().toString();
// get the group identity
final String name = getGroupName(ctx);
// get the value of this group that may associate it to users
final String referencedGroupValue = getReferencedGroupValue(ctx);
if (!StringUtils.isBlank(groupMemberAttribute)) {
Attribute attributeUsers = ctx.getAttributes().get(groupMemberAttribute);
if (attributeUsers == null) {
logger.warn("Group member attribute [" + groupMemberAttribute + "] does not exist. Ignoring group membership.");
} else {
try {
final NamingEnumeration<String> userValues = (NamingEnumeration<String>) attributeUsers.getAll();
while (userValues.hasMoreElements()) {
final String userValue = userValues.next();
if (performUserSearch) {
// find the user by it's referenced attribute and add the identifier to this group
final User user = userLookup.get(userValue);
// ensure the user is known
if (user != null) {
groupToUserIdentifierMappings.computeIfAbsent(referencedGroupValue, g -> new HashSet<>()).add(user.getIdentifier());
} else {
logger.warn(String.format("%s contains member %s but that user was not found while searching users. Ignoring group membership.", name, userValue));
}
} else {
// since performUserSearch is false, then the referenced group attribute must be blank... the user value must be the dn
final String userDn = userValue;
final String userIdentity;
if (useDnForUserIdentity) {
// use the user value to avoid the unnecessary look up
userIdentity = userDn;
} else {
// lookup the user to extract the user identity
userIdentity = getUserIdentity((DirContextAdapter) ldapTemplate.lookup(userDn));
}
// build the user
final User user = new User.Builder().identifierGenerateFromSeed(userIdentity).identity(userIdentity).build();
// add this user
userList.add(user);
groupToUserIdentifierMappings.computeIfAbsent(referencedGroupValue, g -> new HashSet<>()).add(user.getIdentifier());
}
}
} catch (NamingException e) {
throw new AuthorizationAccessException("Error while retrieving group name attribute [" + groupNameAttribute + "].");
}
}
}
// build this group
final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(name).name(name);
// add all users that were associated with this referenced group attribute
if (groupToUserIdentifierMappings.containsKey(referencedGroupValue)) {
groupToUserIdentifierMappings.remove(referencedGroupValue).forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
}
return groupBuilder.build();
}
}, groupProcessor));
} while (hasMorePages(groupProcessor));
// any remaining groupDn's were referenced by a user but not found while searching groups
groupToUserIdentifierMappings.forEach((referencedGroupValue, userIdentifiers) -> {
logger.warn(String.format("[%s] are members of %s but that group was not found while searching users. Ignoring group membership.", StringUtils.join(userIdentifiers, ", "), referencedGroupValue));
});
} else {
// since performGroupSearch is false, then the referenced user attribute must be blank... the group value must be the dn
// groups are not being searched so lookup any groups identified while searching users
groupToUserIdentifierMappings.forEach((groupDn, userIdentifiers) -> {
final String groupName;
if (useDnForGroupName) {
// use the dn to avoid the unnecessary look up
groupName = groupDn;
} else {
groupName = getGroupName((DirContextAdapter) ldapTemplate.lookup(groupDn));
}
// define the group
final Group.Builder groupBuilder = new Group.Builder().identifierGenerateFromSeed(groupName).name(groupName);
// add each user
userIdentifiers.forEach(userIdentifier -> groupBuilder.addUser(userIdentifier));
// build the group
groupList.add(groupBuilder.build());
});
}
// record the updated tenants
tenants.set(new TenantHolder(new HashSet<>(userList), new HashSet<>(groupList)));
} finally {
singleContextSource.destroy();
}
}
use of org.apache.commons.lang3.StringUtils.isBlank in project nifi-registry by apache.
the class CryptoKeyLoader method extractKeyFromBootstrapFile.
/**
* Returns the key (if any) used to encrypt sensitive properties.
* The key extracted from the bootstrap.conf file at the specified location.
*
* @param bootstrapPath the path to the bootstrap file
* @return the key in hexadecimal format, or {@link CryptoKeyProvider#EMPTY_KEY} if the key is null or empty
* @throws IOException if the file is not readable
*/
public static String extractKeyFromBootstrapFile(String bootstrapPath) throws IOException {
File bootstrapFile;
if (StringUtils.isBlank(bootstrapPath)) {
logger.error("Cannot read from bootstrap.conf file to extract encryption key; location not specified");
throw new IOException("Cannot read from bootstrap.conf without file location");
} else {
bootstrapFile = new File(bootstrapPath);
}
String keyValue;
if (bootstrapFile.exists() && bootstrapFile.canRead()) {
try (Stream<String> stream = Files.lines(Paths.get(bootstrapFile.getAbsolutePath()))) {
Optional<String> keyLine = stream.filter(l -> l.startsWith(BOOTSTRAP_KEY_PREFIX)).findFirst();
if (keyLine.isPresent()) {
keyValue = keyLine.get().split("=", 2)[1];
keyValue = checkHexKey(keyValue);
} else {
keyValue = CryptoKeyProvider.EMPTY_KEY;
}
} catch (IOException e) {
logger.error("Cannot read from bootstrap.conf file at {} to extract encryption key", bootstrapFile.getAbsolutePath());
throw new IOException("Cannot read from bootstrap.conf", e);
}
} else {
logger.error("Cannot read from bootstrap.conf file at {} to extract encryption key -- file is missing or permissions are incorrect", bootstrapFile.getAbsolutePath());
throw new IOException("Cannot read from bootstrap.conf");
}
if (CryptoKeyProvider.EMPTY_KEY.equals(keyValue)) {
logger.info("No encryption key present in the bootstrap.conf file at {}", bootstrapFile.getAbsolutePath());
}
return keyValue;
}
use of org.apache.commons.lang3.StringUtils.isBlank in project timbuctoo by HuygensING.
the class TabularUpload method upload.
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@POST
public Response upload(@FormDataParam("file") final InputStream rdfInputStream, @FormDataParam("file") final FormDataBodyPart body, @FormDataParam("file") final FormDataContentDisposition fileInfo, @FormDataParam("fileMimeTypeOverride") final MediaType mimeTypeOverride, FormDataMultiPart formData, @HeaderParam("authorization") final String authHeader, @PathParam("userId") final String ownerId, @PathParam("dataSetId") final String dataSetId, @QueryParam("forceCreation") boolean forceCreation) throws DataStoreCreationException, FileStorageFailedException, ExecutionException, InterruptedException, LogStorageFailedException {
final Either<Response, Response> result = authCheck.getOrCreate(authHeader, ownerId, dataSetId, forceCreation).flatMap(userAndDs -> authCheck.hasAdminAccess(userAndDs.getLeft(), userAndDs.getRight())).map(userAndDs -> {
final MediaType mediaType = mimeTypeOverride == null ? body.getMediaType() : mimeTypeOverride;
Optional<Loader> loader = LoaderFactory.createFor(mediaType.toString(), formData.getFields().entrySet().stream().filter(entry -> entry.getValue().size() > 0).filter(entry -> entry.getValue().get(0) != null).filter(entry -> MediaTypes.typeEqual(MediaType.TEXT_PLAIN_TYPE, entry.getValue().get(0).getMediaType())).collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().get(0).getValue())));
if (!loader.isPresent()) {
return errorResponseHelper.error(400, "We do not support the mediatype '" + mediaType + "'. Make sure to add the correct mediatype to the file " + "parameter. In curl you'd use `-F \"file=@<filename>;type=<mediatype>\"`. In a webbrowser you probably " + "have no way of setting the correct mimetype. So you can use a special parameter to override it: " + "`formData.append(\"fileMimeTypeOverride\", \"<mimetype>\");`");
}
final DataSet dataSet = userAndDs.getRight();
ImportManager importManager = dataSet.getImportManager();
if (StringUtils.isBlank(fileInfo.getName())) {
return Response.status(400).entity("filename cannot be empty.").build();
}
try {
String fileToken = importManager.addFile(rdfInputStream, fileInfo.getFileName(), mediaType);
Future<ImportStatus> promise = importManager.generateLog(dataSet.getMetadata().getBaseUri(), dataSet.getMetadata().getBaseUri(), new TabularRdfCreator(loader.get(), fileToken, fileInfo.getFileName()));
return handleImportManagerResult(promise);
} catch (FileStorageFailedException | LogStorageFailedException e) {
LOG.error("Tabular upload failed", e);
return Response.serverError().build();
}
});
if (result.isLeft()) {
return result.getLeft();
} else {
return result.get();
}
}
use of org.apache.commons.lang3.StringUtils.isBlank in project mule by mulesoft.
the class XmlExtensionLoaderDelegate method declareErrorModels.
private void declareErrorModels(OperationDeclarer operationDeclarer, XmlDslModel xmlDslModel, String operationName, ComponentModel operationModel) {
Optional<ComponentModel> optionalParametersComponentModel = operationModel.getInnerComponents().stream().filter(child -> child.getIdentifier().equals(OPERATION_ERRORS_IDENTIFIER)).findAny();
optionalParametersComponentModel.ifPresent(componentModel -> componentModel.getInnerComponents().stream().filter(child -> child.getIdentifier().equals(OPERATION_ERROR_IDENTIFIER)).forEach(param -> {
final String namespace = xmlDslModel.getPrefix().toUpperCase();
final String typeName = param.getParameters().get(ERROR_TYPE_ATTRIBUTE);
if (StringUtils.isBlank(typeName)) {
throw new IllegalModelDefinitionException(format("The operation [%s] cannot have an <error> with an empty 'type' attribute", operationName));
}
if (typeName.contains(NAMESPACE_SEPARATOR)) {
throw new IllegalModelDefinitionException(format("The operation [%s] cannot have an <error> [%s] that contains a reserved character [%s]", operationName, typeName, NAMESPACE_SEPARATOR));
}
operationDeclarer.withErrorModel(ErrorModelBuilder.newError(typeName, namespace).withParent(ErrorModelBuilder.newError(ANY).build()).build());
}));
}
use of org.apache.commons.lang3.StringUtils.isBlank in project stanbol by apache.
the class KiWiRepositoryService method activate.
@Activate
protected final void activate(ComponentContext context) throws ConfigurationException, RepositoryException {
log.info("activate KiWi repository ...");
if (context == null || context.getProperties() == null) {
throw new IllegalStateException("No valid" + ComponentContext.class + " parsed in activate!");
}
//copy the read-only configuration as we might need to change it before
//adding it to the registered service
final Dictionary<String, Object> config = copyConfig(context);
final BundleContext bc = context.getBundleContext();
//we want to substitute variables used in the dbURL with configuration,
//framework and system properties
StrSubstitutor strSubstitutor = new StrSubstitutor(new StrLookup<Object>() {
@Override
public String lookup(String key) {
Object val = config.get(key);
if (val == null) {
val = bc.getProperty(key);
}
return val.toString();
}
});
String name = (String) config.get(REPOSITORY_ID);
if (StringUtils.isBlank(name)) {
throw new ConfigurationException(REPOSITORY_ID, "The parsed Repository ID MUST NOT be NULL nor blank!");
} else {
log.debug(" - name: {}", name);
}
KiWiDialect dialect;
String db_type;
if (StringUtils.equalsIgnoreCase("postgres", (String) config.get(DB_DIALECT))) {
dialect = new PostgreSQLDialect();
db_type = "postgresql";
} else if (StringUtils.equalsIgnoreCase("mysql", (String) config.get(DB_DIALECT))) {
dialect = new MySQLDialect();
db_type = "mysql";
} else if (StringUtils.equalsIgnoreCase("h2", (String) config.get(DB_DIALECT))) {
dialect = new H2Dialect();
db_type = "h2";
} else {
throw new ConfigurationException(DB_DIALECT, "No valid database dialect was given");
}
log.debug(" - dialect: {}", dialect);
String db_url = (String) config.get(DB_URL);
if (StringUtils.isBlank(db_url)) {
//build the db url from parameters
String db_host = (String) config.get(DB_HOST);
if (StringUtils.isBlank(db_host)) {
db_host = DEFAULT_DB_HOST;
}
log.debug(" - db host: {}", db_host);
String db_name = (String) config.get(DB_NAME);
if (StringUtils.isBlank(db_name)) {
db_name = DEFAULT_DB_NAME;
}
log.debug(" - db name: {}", name);
int db_port;
Object value = config.get(DB_PORT);
if (value instanceof Number) {
db_port = ((Number) value).intValue();
} else if (value != null && !StringUtils.isBlank(value.toString())) {
db_port = Integer.parseInt(value.toString());
} else {
db_port = DEFAULT_DB_PORT;
}
log.debug(" - db port: {}", db_port);
String db_opts = (String) config.get(DB_OPTS);
log.debug(" - db options: {}", db_opts);
StringBuilder dbUrlBuilder = new StringBuilder("jdbc:").append(db_type);
if (dialect instanceof H2Dialect) {
//H2 uses a file path and not a host so we do not need the ://
dbUrlBuilder.append(':').append(db_host);
} else {
dbUrlBuilder.append("://").append(db_host);
}
if (db_port > 0) {
dbUrlBuilder.append(':').append(db_port);
}
if (!StringUtils.isBlank(db_name)) {
dbUrlBuilder.append('/').append(db_name);
}
if (!StringUtils.isBlank(db_opts)) {
dbUrlBuilder.append(db_opts);
}
dbUrl = strSubstitutor.replace(dbUrlBuilder);
} else if (!db_url.startsWith("jdbc:")) {
throw new ConfigurationException(DB_URL, "Database URLs are expected to start with " + "'jdbc:' (parsed: '" + db_url + "')!");
} else {
dbUrl = strSubstitutor.replace(db_url);
}
String db_user = (String) config.get(DB_USER);
if (StringUtils.isBlank(db_user)) {
db_user = DEFAULT_DB_USER;
} else {
db_user = strSubstitutor.replace(db_user);
}
log.debug(" - db user: {}", db_user);
String db_pass = (String) config.get(DB_PASS);
if (StringUtils.isBlank(db_pass)) {
log.debug(" - db pwd is set to default");
db_pass = DEFAULT_DB_PASS;
} else {
log.debug(" - db pwd is set to parsed value");
}
KiWiConfiguration configuration = new KiWiConfiguration("Marmotta KiWi", dbUrl, db_user, db_pass, dialect);
//parse cluster options
String cluster = (String) config.get(CLUSTER);
if (!StringUtils.isBlank(cluster)) {
log.debug(" - cluster: {}", cluster);
configuration.setClustered(true);
configuration.setClusterName(cluster);
String clusterAddress = (String) config.get(CLUSTER_ADDRESS);
if (!StringUtils.isBlank(clusterAddress)) {
configuration.setClusterAddress(strSubstitutor.replace(clusterAddress));
}
log.debug(" - cluster address: {}", configuration.getClusterAddress());
Object clusterPort = config.get(CLUSTER_PORT);
if (clusterPort instanceof Number) {
int port = ((Number) clusterPort).intValue();
if (port > 0) {
configuration.setClusterPort(port);
}
//else use default
} else if (clusterPort != null) {
try {
int port = Integer.parseInt(strSubstitutor.replace(clusterPort));
if (port > 0) {
configuration.setClusterPort(port);
}
} catch (NumberFormatException e) {
throw new ConfigurationException(CLUSTER_PORT, "Unable to parse " + "Cluster Port from configured value '" + clusterPort + "'!", e);
}
}
log.debug(" - cluster port ({})", configuration.getClusterPort());
String cachingBackend = (String) config.get(CACHING_BACKEND);
if (StringUtils.isBlank(cachingBackend)) {
configuration.setCachingBackend(CachingBackends.valueOf(DEFAULT_CACHING_BACKEND));
} else {
try {
configuration.setCachingBackend(CachingBackends.valueOf(strSubstitutor.replace(cachingBackend)));
} catch (IllegalArgumentException e) {
throw new ConfigurationException(CACHING_BACKEND, "Unsupported CachingBackend '" + cachingBackend + "' (supported: " + Arrays.toString(CachingBackends.values()) + ")!", e);
}
}
log.debug(" - caching Backend: {}", configuration.getCachingBackend());
String cacheMode = (String) config.get(CACHE_MODE);
if (StringUtils.isBlank(cacheMode)) {
cacheMode = DEFAULT_CACHE_MODE;
}
try {
configuration.setCacheMode(CacheMode.valueOf(strSubstitutor.replace(cacheMode)));
} catch (IllegalArgumentException e) {
throw new ConfigurationException(CACHE_MODE, "Unsupported CacheMode '" + cacheMode + "' (supported: " + Arrays.toString(CacheMode.values()) + ")!");
}
log.debug(" - cache mode: {}", configuration.getCacheMode());
} else {
// not clustered
log.debug(" - no cluster configured");
configuration.setClustered(false);
}
log.info(" ... initialise KiWi repository: {}", dbUrl);
KiWiStore store = new KiWiStore(configuration);
repository = new SailRepository(new KiWiSparqlSail(store));
repository.initialize();
//set the repository type property to KiWiStore
config.put(SAIL_IMPL, KiWiStore.class.getName());
repoRegistration = context.getBundleContext().registerService(Repository.class.getName(), repository, config);
log.info(" - successfully registered KiWi Repository {}", name);
}
Aggregations