Search in sources :

Example 1 with BooleanUtils.toBoolean

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:
        }
    }
}
Also used : Date(java.util.Date) Realm(org.apache.syncope.core.persistence.api.entity.Realm) PlainAttr(org.apache.syncope.core.persistence.api.entity.PlainAttr) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Schema(org.apache.syncope.core.persistence.api.entity.Schema) InvalidPasswordRuleConf(org.apache.syncope.core.provisioning.api.utils.policy.InvalidPasswordRuleConf) StringUtils(org.apache.commons.lang3.StringUtils) Attribute(org.identityconnectors.framework.common.objects.Attribute) GroupDAO(org.apache.syncope.core.persistence.api.dao.GroupDAO) Pair(org.apache.commons.lang3.tuple.Pair) AttrSchemaType(org.apache.syncope.common.lib.types.AttrSchemaType) AnyObjectDAO(org.apache.syncope.core.persistence.api.dao.AnyObjectDAO) ConnObjectUtils(org.apache.syncope.core.provisioning.java.utils.ConnObjectUtils) GroupableRelatableTO(org.apache.syncope.common.lib.to.GroupableRelatableTO) OrgUnit(org.apache.syncope.core.persistence.api.entity.resource.OrgUnit) ParseException(java.text.ParseException) OperationalAttributes(org.identityconnectors.framework.common.objects.OperationalAttributes) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) OrgUnitItem(org.apache.syncope.core.persistence.api.entity.resource.OrgUnitItem) DerAttrHandler(org.apache.syncope.core.provisioning.api.DerAttrHandler) Set(java.util.Set) PlainAttrValue(org.apache.syncope.core.persistence.api.entity.PlainAttrValue) GroupTO(org.apache.syncope.common.lib.to.GroupTO) AnyTypeDAO(org.apache.syncope.core.persistence.api.dao.AnyTypeDAO) MappingItem(org.apache.syncope.core.persistence.api.entity.resource.MappingItem) List(java.util.List) DerSchemaDAO(org.apache.syncope.core.persistence.api.dao.DerSchemaDAO) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) AttributeUtil(org.identityconnectors.framework.common.objects.AttributeUtil) AttributeBuilder(org.identityconnectors.framework.common.objects.AttributeBuilder) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) Group(org.apache.syncope.core.persistence.api.entity.group.Group) Optional(java.util.Optional) IntAttrName(org.apache.syncope.core.provisioning.api.IntAttrName) VirAttrCache(org.apache.syncope.core.provisioning.api.cache.VirAttrCache) ApplicationDAO(org.apache.syncope.core.persistence.api.dao.ApplicationDAO) ItemTransformer(org.apache.syncope.core.provisioning.api.data.ItemTransformer) AttrTO(org.apache.syncope.common.lib.to.AttrTO) AnyUtilsFactory(org.apache.syncope.core.persistence.api.entity.AnyUtilsFactory) RealmTO(org.apache.syncope.common.lib.to.RealmTO) GroupableRelatable(org.apache.syncope.core.persistence.api.entity.GroupableRelatable) AnyTO(org.apache.syncope.common.lib.to.AnyTO) FrameworkUtil(org.identityconnectors.framework.common.FrameworkUtil) BooleanUtils(org.apache.commons.lang3.BooleanUtils) PasswordGenerator(org.apache.syncope.core.spring.security.PasswordGenerator) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Application(org.apache.syncope.core.persistence.api.entity.Application) DerSchema(org.apache.syncope.core.persistence.api.entity.DerSchema) MappingManager(org.apache.syncope.core.provisioning.api.MappingManager) FieldUtils(org.apache.commons.lang3.reflect.FieldUtils) Item(org.apache.syncope.core.persistence.api.entity.resource.Item) RealmDAO(org.apache.syncope.core.persistence.api.dao.RealmDAO) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) Mapping(org.apache.syncope.core.persistence.api.entity.resource.Mapping) Encryptor(org.apache.syncope.core.spring.security.Encryptor) Logger(org.slf4j.Logger) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) PlainSchemaDAO(org.apache.syncope.core.persistence.api.dao.PlainSchemaDAO) VirAttrHandler(org.apache.syncope.core.provisioning.api.VirAttrHandler) User(org.apache.syncope.core.persistence.api.entity.user.User) Membership(org.apache.syncope.core.persistence.api.entity.Membership) Name(org.identityconnectors.framework.common.objects.Name) VirSchema(org.apache.syncope.core.persistence.api.entity.VirSchema) MappingUtils(org.apache.syncope.core.provisioning.java.utils.MappingUtils) Component(org.springframework.stereotype.Component) VirSchemaDAO(org.apache.syncope.core.persistence.api.dao.VirSchemaDAO) UserTO(org.apache.syncope.common.lib.to.UserTO) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) Collections(java.util.Collections) Any(org.apache.syncope.core.persistence.api.entity.Any) DateFormatUtils(org.apache.commons.lang3.time.DateFormatUtils) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) ParsingValidationException(org.apache.syncope.core.persistence.api.attrvalue.validation.ParsingValidationException) Transactional(org.springframework.transaction.annotation.Transactional) Group(org.apache.syncope.core.persistence.api.entity.group.Group) Optional(java.util.Optional) ItemTransformer(org.apache.syncope.core.provisioning.api.data.ItemTransformer) AttrTO(org.apache.syncope.common.lib.to.AttrTO) IntAttrName(org.apache.syncope.core.provisioning.api.IntAttrName) GroupTO(org.apache.syncope.common.lib.to.GroupTO) ParsingValidationException(org.apache.syncope.core.persistence.api.attrvalue.validation.ParsingValidationException) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) GroupableRelatableTO(org.apache.syncope.common.lib.to.GroupableRelatableTO) UserTO(org.apache.syncope.common.lib.to.UserTO) AttrSchemaType(org.apache.syncope.common.lib.types.AttrSchemaType) MembershipTO(org.apache.syncope.common.lib.to.MembershipTO) PlainAttrValue(org.apache.syncope.core.persistence.api.entity.PlainAttrValue) AnyObject(org.apache.syncope.core.persistence.api.entity.anyobject.AnyObject) ParseException(java.text.ParseException) PlainSchema(org.apache.syncope.core.persistence.api.entity.PlainSchema) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with BooleanUtils.toBoolean

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;
}
Also used : ProgramMessageService(org.hisp.dhis.program.message.ProgramMessageService) NotificationMessageRenderer(org.hisp.dhis.notification.NotificationMessageRenderer) Date(java.util.Date) MessageConversationParams(org.hisp.dhis.message.MessageConversationParams) RequiredArgsConstructor(lombok.RequiredArgsConstructor) BatchResponseStatus(org.hisp.dhis.outboundmessage.BatchResponseStatus) ProgramMessage(org.hisp.dhis.program.message.ProgramMessage) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ProgramStageInstance(org.hisp.dhis.program.ProgramStageInstance) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) MessageService(org.hisp.dhis.message.MessageService) StringUtils(org.apache.commons.lang3.StringUtils) ProgramMessageRecipients(org.hisp.dhis.program.message.ProgramMessageRecipients) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) Service(org.springframework.stereotype.Service) EventDataValue(org.hisp.dhis.eventdatavalue.EventDataValue) ProgramInstance(org.hisp.dhis.program.ProgramInstance) User(org.hisp.dhis.user.User) Nullable(javax.annotation.Nullable) NotificationTemplateMapper(org.hisp.dhis.program.notification.template.snapshot.NotificationTemplateMapper) MessageType(org.hisp.dhis.message.MessageType) Predicate(java.util.function.Predicate) NonNull(lombok.NonNull) ProgramInstanceStore(org.hisp.dhis.program.ProgramInstanceStore) UserGroup(org.hisp.dhis.user.UserGroup) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance) Set(java.util.Set) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Clock(org.hisp.dhis.system.util.Clock) Builder(lombok.Builder) PROGRAM_RULE(org.hisp.dhis.program.notification.NotificationTrigger.PROGRAM_RULE) DeliveryChannel(org.hisp.dhis.common.DeliveryChannel) Data(lombok.Data) Optional(java.util.Optional) ProgramStageInstanceStore(org.hisp.dhis.program.ProgramStageInstanceStore) Collections(java.util.Collections) NotificationMessage(org.hisp.dhis.notification.NotificationMessage) DateUtils(org.hisp.dhis.util.DateUtils) Transactional(org.springframework.transaction.annotation.Transactional) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) User(org.hisp.dhis.user.User) Set(java.util.Set) UserGroup(org.hisp.dhis.user.UserGroup)

Example 3 with BooleanUtils.toBoolean

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;
}
Also used : NotificationMessageRenderer(org.hisp.dhis.notification.NotificationMessageRenderer) SortedSet(java.util.SortedSet) Importance(org.hisp.dhis.validation.Importance) Date(java.util.Date) HashMap(java.util.HashMap) BooleanUtils(org.apache.commons.lang3.BooleanUtils) SendStrategy(org.hisp.dhis.notification.SendStrategy) MessageService(org.hisp.dhis.message.MessageService) Function(java.util.function.Function) ValidationResult(org.hisp.dhis.validation.ValidationResult) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) HIGH(org.hisp.dhis.validation.Importance.HIGH) Service(org.springframework.stereotype.Service) Map(java.util.Map) HashCodeBuilder(org.apache.commons.lang3.builder.HashCodeBuilder) User(org.hisp.dhis.user.User) EqualsBuilder(org.apache.commons.lang3.builder.EqualsBuilder) LOW(org.hisp.dhis.validation.Importance.LOW) BiMap(com.google.common.collect.BiMap) LN(org.hisp.dhis.commons.util.TextUtils.LN) MessageConversationPriority(org.hisp.dhis.message.MessageConversationPriority) Predicate(java.util.function.Predicate) ValidationResultService(org.hisp.dhis.validation.ValidationResultService) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) Set(java.util.Set) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) CompareToBuilder(org.apache.commons.lang3.builder.CompareToBuilder) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) Slf4j(lombok.extern.slf4j.Slf4j) Clock(org.hisp.dhis.system.util.Clock) HashBiMap(com.google.common.collect.HashBiMap) MEDIUM(org.hisp.dhis.validation.Importance.MEDIUM) NotificationMessage(org.hisp.dhis.notification.NotificationMessage) DateUtils(org.hisp.dhis.util.DateUtils) Transactional(org.springframework.transaction.annotation.Transactional) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) User(org.hisp.dhis.user.User) SortedSet(java.util.SortedSet) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) Set(java.util.Set) ValidationResult(org.hisp.dhis.validation.ValidationResult)

Example 4 with BooleanUtils.toBoolean

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();
            }
        });
    }
}
Also used : Page(org.apache.wicket.Page) FileAlterationObserver(org.apache.commons.io.monitor.FileAlterationObserver) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ClassPathScanImplementationLookup(org.apache.syncope.client.enduser.init.ClassPathScanImplementationLookup) SyncopeClientFactoryBean(org.apache.syncope.client.lib.SyncopeClientFactoryBean) StringUtils(org.apache.commons.lang3.StringUtils) FileAlterationListenerAdaptor(org.apache.commons.io.monitor.FileAlterationListenerAdaptor) IResource(org.apache.wicket.request.resource.IResource) Map(java.util.Map) HomePage(org.apache.syncope.client.enduser.pages.HomePage) Response(org.apache.wicket.request.Response) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Request(org.apache.wicket.request.Request) ResourceReference(org.apache.wicket.request.resource.ResourceReference) SyncopeConstants(org.apache.syncope.common.lib.SyncopeConstants) Properties(java.util.Properties) Logger(org.slf4j.Logger) FileAlterationListener(org.apache.commons.io.monitor.FileAlterationListener) FileAlterationMonitor(org.apache.commons.io.monitor.FileAlterationMonitor) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) Args(org.apache.wicket.util.lang.Args) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) AbstractResource(org.apache.wicket.request.resource.AbstractResource) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) File(java.io.File) Serializable(java.io.Serializable) PropertyUtils(org.apache.syncope.common.lib.PropertyUtils) WebApplication(org.apache.wicket.protocol.http.WebApplication) CaptchaResource(org.apache.syncope.client.enduser.resources.CaptchaResource) Session(org.apache.wicket.Session) CustomAttributesInfo(org.apache.syncope.client.enduser.model.CustomAttributesInfo) Resource(org.apache.syncope.client.enduser.annotations.Resource) EnduserInitializer(org.apache.syncope.client.enduser.init.EnduserInitializer) InputStream(java.io.InputStream) FileAlterationMonitor(org.apache.commons.io.monitor.FileAlterationMonitor) AbstractResource(org.apache.wicket.request.resource.AbstractResource) CaptchaResource(org.apache.syncope.client.enduser.resources.CaptchaResource) Properties(java.util.Properties) FileAlterationObserver(org.apache.commons.io.monitor.FileAlterationObserver) ClassPathScanImplementationLookup(org.apache.syncope.client.enduser.init.ClassPathScanImplementationLookup) SyncopeClientFactoryBean(org.apache.syncope.client.lib.SyncopeClientFactoryBean) FileAlterationListener(org.apache.commons.io.monitor.FileAlterationListener) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ResourceReference(org.apache.wicket.request.resource.ResourceReference) CustomAttributesInfo(org.apache.syncope.client.enduser.model.CustomAttributesInfo) InputStream(java.io.InputStream) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) IResource(org.apache.wicket.request.resource.IResource) AbstractResource(org.apache.wicket.request.resource.AbstractResource) CaptchaResource(org.apache.syncope.client.enduser.resources.CaptchaResource) Resource(org.apache.syncope.client.enduser.annotations.Resource) IOException(java.io.IOException) WicketRuntimeException(org.apache.wicket.WicketRuntimeException) IOException(java.io.IOException) FileAlterationListenerAdaptor(org.apache.commons.io.monitor.FileAlterationListenerAdaptor) File(java.io.File) IResource(org.apache.wicket.request.resource.IResource)

Example 5 with BooleanUtils.toBoolean

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);
}
Also used : HashMap(java.util.HashMap) TrackImpl(org.opencastproject.mediapackage.track.TrackImpl) MediaPackage(org.opencastproject.mediapackage.MediaPackage) WorkflowOperationException(org.opencastproject.workflow.api.WorkflowOperationException) VideoStream(org.opencastproject.mediapackage.VideoStream) Fraction(org.apache.commons.lang3.math.Fraction) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) Track(org.opencastproject.mediapackage.Track)

Aggregations

BooleanUtils (org.apache.commons.lang3.BooleanUtils)5 StringUtils (org.apache.commons.lang3.StringUtils)4 Date (java.util.Date)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 Set (java.util.Set)3 Collectors (java.util.stream.Collectors)3 Slf4j (lombok.extern.slf4j.Slf4j)3 Transactional (org.springframework.transaction.annotation.Transactional)3 Sets (com.google.common.collect.Sets)2 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 HashSet (java.util.HashSet)2 Objects (java.util.Objects)2 Optional (java.util.Optional)2 Predicate (java.util.function.Predicate)2 RequiredArgsConstructor (lombok.RequiredArgsConstructor)2 MessageService (org.hisp.dhis.message.MessageService)2 NotificationMessage (org.hisp.dhis.notification.NotificationMessage)2