use of org.apache.commons.lang3.BooleanUtils.toBoolean in project syncope by apache.
the class MappingManagerImpl method setIntValues.
@Transactional(readOnly = true)
@Override
public void setIntValues(final Item mapItem, final Attribute attr, final AnyTO anyTO, final AnyUtils anyUtils) {
List<Object> values = null;
if (attr != null) {
values = attr.getValue();
for (ItemTransformer transformer : MappingUtils.getItemTransformers(mapItem)) {
values = transformer.beforePull(mapItem, anyTO, values);
}
}
values = values == null ? Collections.emptyList() : values;
IntAttrName intAttrName;
try {
intAttrName = intAttrNameParser.parse(mapItem.getIntAttrName(), anyUtils.getAnyTypeKind());
} catch (ParseException e) {
LOG.error("Invalid intAttrName '{}' specified, ignoring", mapItem.getIntAttrName(), e);
return;
}
if (intAttrName.getField() != null) {
switch(intAttrName.getField()) {
case "password":
if (anyTO instanceof UserTO && !values.isEmpty()) {
((UserTO) anyTO).setPassword(ConnObjectUtils.getPassword(values.get(0)));
}
break;
case "username":
if (anyTO instanceof UserTO) {
((UserTO) anyTO).setUsername(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString());
}
break;
case "name":
if (anyTO instanceof GroupTO) {
((GroupTO) anyTO).setName(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString());
} else if (anyTO instanceof AnyObjectTO) {
((AnyObjectTO) anyTO).setName(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString());
}
break;
case "mustChangePassword":
if (anyTO instanceof UserTO && !values.isEmpty() && values.get(0) != null) {
((UserTO) anyTO).setMustChangePassword(BooleanUtils.toBoolean(values.get(0).toString()));
}
break;
case "userOwner":
case "groupOwner":
if (anyTO instanceof GroupTO && attr != null) {
// using a special attribute (with schema "", that will be ignored) for carrying the
// GroupOwnerSchema value
AttrTO attrTO = new AttrTO();
attrTO.setSchema(StringUtils.EMPTY);
if (values.isEmpty() || values.get(0) == null) {
attrTO.getValues().add(StringUtils.EMPTY);
} else {
attrTO.getValues().add(values.get(0).toString());
}
((GroupTO) anyTO).getPlainAttrs().add(attrTO);
}
break;
default:
}
} else if (intAttrName.getSchemaType() != null) {
GroupableRelatableTO groupableTO = null;
Group group = null;
if (anyTO instanceof GroupableRelatableTO && intAttrName.getMembershipOfGroup() != null) {
groupableTO = (GroupableRelatableTO) anyTO;
group = groupDAO.findByName(intAttrName.getMembershipOfGroup());
}
switch(intAttrName.getSchemaType()) {
case PLAIN:
AttrTO attrTO = new AttrTO();
attrTO.setSchema(intAttrName.getSchemaName());
PlainSchema schema = plainSchemaDAO.find(intAttrName.getSchemaName());
for (Object value : values) {
AttrSchemaType schemaType = schema == null ? AttrSchemaType.String : schema.getType();
if (value != null) {
PlainAttrValue attrValue = anyUtils.newPlainAttrValue();
switch(schemaType) {
case String:
attrValue.setStringValue(value.toString());
break;
case Binary:
attrValue.setBinaryValue((byte[]) value);
break;
default:
try {
attrValue.parseValue(schema, value.toString());
} catch (ParsingValidationException e) {
LOG.error("While parsing provided value {}", value, e);
attrValue.setStringValue(value.toString());
schemaType = AttrSchemaType.String;
}
break;
}
attrTO.getValues().add(attrValue.getValueAsString(schemaType));
}
}
if (groupableTO == null || group == null) {
anyTO.getPlainAttrs().add(attrTO);
} else {
Optional<MembershipTO> membership = groupableTO.getMembership(group.getKey());
if (!membership.isPresent()) {
membership = Optional.of(new MembershipTO.Builder().group(group.getKey(), group.getName()).build());
groupableTO.getMemberships().add(membership.get());
}
membership.get().getPlainAttrs().add(attrTO);
}
break;
case DERIVED:
attrTO = new AttrTO();
attrTO.setSchema(intAttrName.getSchemaName());
if (groupableTO == null || group == null) {
anyTO.getDerAttrs().add(attrTO);
} else {
Optional<MembershipTO> membership = groupableTO.getMembership(group.getKey());
if (!membership.isPresent()) {
membership = Optional.of(new MembershipTO.Builder().group(group.getKey(), group.getName()).build());
groupableTO.getMemberships().add(membership.get());
}
membership.get().getDerAttrs().add(attrTO);
}
break;
case VIRTUAL:
attrTO = new AttrTO();
attrTO.setSchema(intAttrName.getSchemaName());
// virtual attributes don't get transformed, iterate over original attr.getValue()
if (attr != null && attr.getValue() != null && !attr.getValue().isEmpty()) {
attr.getValue().stream().filter(value -> value != null).forEachOrdered(value -> attrTO.getValues().add(value.toString()));
}
if (groupableTO == null || group == null) {
anyTO.getVirAttrs().add(attrTO);
} else {
Optional<MembershipTO> membership = groupableTO.getMembership(group.getKey());
if (!membership.isPresent()) {
membership = Optional.of(new MembershipTO.Builder().group(group.getKey(), group.getName()).build());
groupableTO.getMemberships().add(membership.get());
}
membership.get().getVirAttrs().add(attrTO);
}
break;
default:
}
}
}
use of org.apache.commons.lang3.BooleanUtils.toBoolean in project dhis2-core by dhis2.
the class DefaultProgramNotificationService method resolveDhisMessageRecipients.
private Set<User> resolveDhisMessageRecipients(ProgramNotificationTemplate template, @Nullable ProgramInstance programInstance, @Nullable ProgramStageInstance programStageInstance) {
if (programInstance == null && programStageInstance == null) {
throw new IllegalArgumentException("Either of the arguments [programInstance, programStageInstance] must be non-null");
}
Set<User> recipients = Sets.newHashSet();
OrganisationUnit eventOrgUnit = programInstance != null ? programInstance.getOrganisationUnit() : programStageInstance.getOrganisationUnit();
Set<OrganisationUnit> orgUnitInHierarchy = Sets.newHashSet();
ProgramNotificationRecipient recipientType = template.getNotificationRecipient();
if (recipientType == ProgramNotificationRecipient.USER_GROUP) {
recipients = Optional.ofNullable(template).map(ProgramNotificationTemplate::getRecipientUserGroup).map(UserGroup::getMembers).orElse(recipients);
final boolean limitToHierarchy = BooleanUtils.toBoolean(template.getNotifyUsersInHierarchyOnly());
final boolean parentOrgUnitOnly = BooleanUtils.toBoolean(template.getNotifyParentOrganisationUnitOnly());
if (limitToHierarchy) {
orgUnitInHierarchy.add(eventOrgUnit);
orgUnitInHierarchy.addAll(eventOrgUnit.getAncestors());
recipients = recipients.stream().filter(r -> orgUnitInHierarchy.contains(r.getOrganisationUnit())).collect(Collectors.toSet());
return recipients;
} else if (parentOrgUnitOnly) {
Set<User> parents = Sets.newHashSet();
recipients.forEach(r -> parents.addAll(r.getOrganisationUnit().getParent().getUsers()));
return parents;
}
recipients.addAll(template.getRecipientUserGroup().getMembers());
} else if (recipientType == ProgramNotificationRecipient.USERS_AT_ORGANISATION_UNIT) {
recipients.addAll(eventOrgUnit.getUsers());
}
return recipients;
}
use of org.apache.commons.lang3.BooleanUtils.toBoolean in project dhis2-core by dhis2.
the class DefaultValidationNotificationService method resolveRecipients.
/**
* Resolve all distinct recipients for the given MessagePair.
*/
private static Set<User> resolveRecipients(MessagePair pair) {
ValidationResult validationResult = pair.result;
ValidationNotificationTemplate template = pair.template;
// Limit recipients to be withing org unit hierarchy only, effectively
// producing a cross-cut of all users in the configured user groups.
final boolean limitToHierarchy = BooleanUtils.toBoolean(template.getNotifyUsersInHierarchyOnly());
final boolean parentOrgUnitOnly = BooleanUtils.toBoolean(template.getNotifyParentOrganisationUnitOnly());
Set<OrganisationUnit> orgUnitsToInclude = Sets.newHashSet();
Set<User> recipients = template.getRecipientUserGroups().stream().flatMap(ug -> ug.getMembers().stream()).collect(Collectors.toSet());
if (limitToHierarchy) {
// Include
orgUnitsToInclude.add(validationResult.getOrganisationUnit());
// self
orgUnitsToInclude.addAll(validationResult.getOrganisationUnit().getAncestors());
recipients = recipients.stream().filter(user -> orgUnitsToInclude.contains(user.getOrganisationUnit())).collect(Collectors.toSet());
} else if (parentOrgUnitOnly) {
Set<User> parents = Sets.newHashSet();
recipients.forEach(user -> parents.addAll(user.getOrganisationUnit().getParent().getUsers()));
return parents;
}
return recipients;
}
use of org.apache.commons.lang3.BooleanUtils.toBoolean in project syncope by apache.
the class SyncopeEnduserApplication method init.
@Override
protected void init() {
super.init();
// read enduser.properties
Properties props = PropertyUtils.read(getClass(), ENDUSER_PROPERTIES, "enduser.directory").getLeft();
domain = props.getProperty("domain", SyncopeConstants.MASTER_DOMAIN);
adminUser = props.getProperty("adminUser");
Args.notNull(adminUser, "<adminUser>");
anonymousUser = props.getProperty("anonymousUser");
Args.notNull(anonymousUser, "<anonymousUser>");
anonymousKey = props.getProperty("anonymousKey");
Args.notNull(anonymousKey, "<anonymousKey>");
captchaEnabled = Boolean.parseBoolean(props.getProperty("captcha"));
Args.notNull(captchaEnabled, "<captcha>");
xsrfEnabled = Boolean.parseBoolean(props.getProperty("xsrf"));
Args.notNull(xsrfEnabled, "<xsrf>");
String scheme = props.getProperty("scheme");
Args.notNull(scheme, "<scheme>");
String host = props.getProperty("host");
Args.notNull(host, "<host>");
String port = props.getProperty("port");
Args.notNull(port, "<port>");
String rootPath = props.getProperty("rootPath");
Args.notNull(rootPath, "<rootPath>");
String useGZIPCompression = props.getProperty("useGZIPCompression");
Args.notNull(useGZIPCompression, "<useGZIPCompression>");
maxUploadFileSizeMB = props.getProperty("maxUploadFileSizeMB") == null ? null : Integer.valueOf(props.getProperty("maxUploadFileSizeMB"));
clientFactory = new SyncopeClientFactoryBean().setAddress(scheme + "://" + host + ":" + port + "/" + rootPath).setContentType(SyncopeClientFactoryBean.ContentType.JSON).setUseCompression(BooleanUtils.toBoolean(useGZIPCompression));
// read customForm.json
try (InputStream is = getClass().getResourceAsStream("/" + CUSTOM_FORM_FILE)) {
customForm = MAPPER.readValue(is, new TypeReference<HashMap<String, CustomAttributesInfo>>() {
});
File enduserDir = new File(props.getProperty("enduser.directory"));
boolean existsEnduserDir = enduserDir.exists() && enduserDir.canRead() && enduserDir.isDirectory();
if (existsEnduserDir) {
File customFormFile = FileUtils.getFile(enduserDir, CUSTOM_FORM_FILE);
if (customFormFile.exists() && customFormFile.canRead() && customFormFile.isFile()) {
customForm = MAPPER.readValue(FileUtils.openInputStream(customFormFile), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
});
}
}
FileAlterationObserver observer = existsEnduserDir ? new FileAlterationObserver(enduserDir, pathname -> StringUtils.contains(pathname.getPath(), CUSTOM_FORM_FILE)) : new FileAlterationObserver(getClass().getResource("/" + CUSTOM_FORM_FILE).getFile(), pathname -> StringUtils.contains(pathname.getPath(), CUSTOM_FORM_FILE));
FileAlterationMonitor monitor = new FileAlterationMonitor(5000);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
@Override
public void onFileChange(final File file) {
try {
LOG.trace("{} has changed. Reloading form customization configuration.", CUSTOM_FORM_FILE);
customForm = MAPPER.readValue(FileUtils.openInputStream(file), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
});
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
@Override
public void onFileCreate(final File file) {
try {
LOG.trace("{} has been created. Loading form customization configuration.", CUSTOM_FORM_FILE);
customForm = MAPPER.readValue(FileUtils.openInputStream(file), new TypeReference<HashMap<String, CustomAttributesInfo>>() {
});
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
@Override
public void onFileDelete(final File file) {
LOG.trace("{} has been deleted. Resetting form customization configuration.", CUSTOM_FORM_FILE);
customForm = null;
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
} catch (Exception e) {
throw new WicketRuntimeException("Could not read " + CUSTOM_FORM_FILE, e);
}
// mount resources
ClassPathScanImplementationLookup classPathScanImplementationLookup = (ClassPathScanImplementationLookup) getServletContext().getAttribute(EnduserInitializer.CLASSPATH_LOOKUP);
for (final Class<? extends AbstractResource> resource : classPathScanImplementationLookup.getResources()) {
Resource annotation = resource.getAnnotation(Resource.class);
if (annotation == null) {
LOG.debug("No @Resource annotation found on {}, ignoring", resource.getName());
} else {
try {
final AbstractResource instance = resource.newInstance();
mountResource(annotation.path(), new ResourceReference(annotation.key()) {
private static final long serialVersionUID = -128426276529456602L;
@Override
public IResource getResource() {
return instance;
}
});
} catch (Exception e) {
LOG.error("Could not instantiate {}", resource.getName(), e);
}
}
}
// mount captcha resource only if captcha is enabled
if (captchaEnabled) {
mountResource("/api/captcha", new ResourceReference("captcha") {
private static final long serialVersionUID = -128426276529456602L;
@Override
public IResource getResource() {
return new CaptchaResource();
}
});
}
}
use of org.apache.commons.lang3.BooleanUtils.toBoolean in project opencast by opencast.
the class AnalyzeTracksWorkflowOperationHandler method start.
@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context) throws WorkflowOperationException {
logger.info("Running analyze-tracks workflow operation on workflow {}", workflowInstance.getId());
final MediaPackage mediaPackage = workflowInstance.getMediaPackage();
final String sourceFlavor = getConfig(workflowInstance, OPT_SOURCE_FLAVOR);
Map<String, String> properties = new HashMap<>();
final MediaPackageElementFlavor flavor = MediaPackageElementFlavor.parseFlavor(sourceFlavor);
final Track[] tracks = mediaPackage.getTracks(flavor);
if (tracks.length <= 0) {
if (BooleanUtils.toBoolean(getConfig(workflowInstance, OPT_FAIL_NO_TRACK, "false"))) {
throw new WorkflowOperationException("No matching tracks for flavor " + sourceFlavor);
}
logger.info("No tracks with specified flavors ({}) to analyse.", sourceFlavor);
return createResult(mediaPackage, properties, Action.CONTINUE, 0);
}
List<Fraction> aspectRatios = getAspectRatio(getConfig(workflowInstance, OPT_VIDEO_ASPECT, ""));
for (Track track : tracks) {
final String varName = toVariableName(track.getFlavor());
properties.put(varName + "_media", "true");
properties.put(varName + "_video", Boolean.toString(track.hasVideo()));
properties.put(varName + "_audio", Boolean.toString(track.hasAudio()));
// Check resolution
if (track.hasVideo()) {
for (VideoStream video : ((TrackImpl) track).getVideo()) {
// Set resolution variables
properties.put(varName + "_resolution_x", video.getFrameWidth().toString());
properties.put(varName + "_resolution_y", video.getFrameHeight().toString());
Fraction trackAspect = Fraction.getReducedFraction(video.getFrameWidth(), video.getFrameHeight());
properties.put(varName + "_aspect", trackAspect.toString());
properties.put(varName + "_framerate", video.getFrameRate().toString());
// Check if we should fall back to nearest defined aspect ratio
if (!aspectRatios.isEmpty()) {
trackAspect = getNearestAspectRatio(trackAspect, aspectRatios);
properties.put(varName + "_aspect_snap", trackAspect.toString());
}
}
}
}
logger.info("Finished analyze-tracks workflow operation adding the properties: {}", properties);
return createResult(mediaPackage, properties, Action.CONTINUE, 0);
}
Aggregations