Search in sources :

Example 61 with StringUtils.isBlank

use of org.apache.commons.lang3.StringUtils.isBlank in project syncope by apache.

the class ConnObjectUtils method getAnyTO.

/**
 * Build a UserTO / GroupTO / AnyObjectTO out of connector object attributes and schema mapping.
 *
 * @param obj connector object
 * @param pullTask pull task
 * @param provision provision information
 * @param anyUtils utils
 * @param <T> any object
 * @return UserTO for the user to be created
 */
@Transactional(readOnly = true)
public <T extends AnyTO> T getAnyTO(final ConnectorObject obj, final PullTask pullTask, final Provision provision, final AnyUtils anyUtils) {
    T anyTO = getAnyTOFromConnObject(obj, pullTask, provision, anyUtils);
    // (for users) if password was not set above, generate if resource is configured for that
    if (anyTO instanceof UserTO && StringUtils.isBlank(((UserTO) anyTO).getPassword()) && provision.getResource().isRandomPwdIfNotProvided()) {
        UserTO userTO = (UserTO) anyTO;
        List<PasswordPolicy> passwordPolicies = new ArrayList<>();
        Realm realm = realmDAO.findByFullPath(userTO.getRealm());
        if (realm != null) {
            realmDAO.findAncestors(realm).stream().filter(ancestor -> ancestor.getPasswordPolicy() != null).forEach(ancestor -> {
                passwordPolicies.add(ancestor.getPasswordPolicy());
            });
        }
        userTO.getResources().stream().map(resource -> resourceDAO.find(resource)).filter(resource -> resource != null && resource.getPasswordPolicy() != null).forEach(resource -> {
            passwordPolicies.add(resource.getPasswordPolicy());
        });
        String password;
        try {
            password = passwordGenerator.generate(passwordPolicies);
        } catch (InvalidPasswordRuleConf e) {
            LOG.error("Could not generate policy-compliant random password for {}", userTO, e);
            password = SecureRandomUtils.generateRandomPassword(16);
        }
        userTO.setPassword(password);
    }
    return anyTO;
}
Also used : AttrTO(org.apache.syncope.common.lib.to.AttrTO) Realm(org.apache.syncope.core.persistence.api.entity.Realm) RealmTO(org.apache.syncope.common.lib.to.RealmTO) LoggerFactory(org.slf4j.LoggerFactory) AnyTO(org.apache.syncope.common.lib.to.AnyTO) Autowired(org.springframework.beans.factory.annotation.Autowired) ConnObjectTO(org.apache.syncope.common.lib.to.ConnObjectTO) PasswordGenerator(org.apache.syncope.core.spring.security.PasswordGenerator) InvalidPasswordRuleConf(org.apache.syncope.core.provisioning.api.utils.policy.InvalidPasswordRuleConf) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) PasswordPolicy(org.apache.syncope.core.persistence.api.entity.policy.PasswordPolicy) GuardedString(org.identityconnectors.common.security.GuardedString) Attribute(org.identityconnectors.framework.common.objects.Attribute) PullTask(org.apache.syncope.core.persistence.api.entity.task.PullTask) Base64(org.identityconnectors.common.Base64) MappingManager(org.apache.syncope.core.provisioning.api.MappingManager) SecurityUtil(org.identityconnectors.common.security.SecurityUtil) RealmDAO(org.apache.syncope.core.persistence.api.dao.RealmDAO) OrgUnit(org.apache.syncope.core.persistence.api.entity.resource.OrgUnit) AnyPatch(org.apache.syncope.common.lib.patch.AnyPatch) Encryptor(org.apache.syncope.core.spring.security.Encryptor) Logger(org.slf4j.Logger) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) GuardedByteArray(org.identityconnectors.common.security.GuardedByteArray) Set(java.util.Set) User(org.apache.syncope.core.persistence.api.entity.user.User) GroupTO(org.apache.syncope.common.lib.to.GroupTO) SecureRandomUtils(org.apache.syncope.core.spring.security.SecureRandomUtils) ConnectorObject(org.identityconnectors.framework.common.objects.ConnectorObject) List(java.util.List) Provision(org.apache.syncope.core.persistence.api.entity.resource.Provision) Component(org.springframework.stereotype.Component) UserTO(org.apache.syncope.common.lib.to.UserTO) AnyUtils(org.apache.syncope.core.persistence.api.entity.AnyUtils) ExternalResourceDAO(org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO) AnyOperations(org.apache.syncope.common.lib.AnyOperations) AnyObjectTO(org.apache.syncope.common.lib.to.AnyObjectTO) Transactional(org.springframework.transaction.annotation.Transactional) InvalidPasswordRuleConf(org.apache.syncope.core.provisioning.api.utils.policy.InvalidPasswordRuleConf) UserTO(org.apache.syncope.common.lib.to.UserTO) PasswordPolicy(org.apache.syncope.core.persistence.api.entity.policy.PasswordPolicy) ArrayList(java.util.ArrayList) GuardedString(org.identityconnectors.common.security.GuardedString) Realm(org.apache.syncope.core.persistence.api.entity.Realm) Transactional(org.springframework.transaction.annotation.Transactional)

Example 62 with StringUtils.isBlank

use of org.apache.commons.lang3.StringUtils.isBlank in project herd by FINRAOS.

the class NamespaceSecurityHelper method checkPermission.

/**
 * Checks the current user's permissions against the given namespace.
 *
 * @param namespace The namespace
 * @param permissions The permissions the current user must have for the given namespace
 */
public void checkPermission(String namespace, NamespacePermissionEnum[] permissions) {
    // Skip the permission check if there is no authentication or namespace is not specified.
    if (!isAuthenticated() || StringUtils.isBlank(namespace)) {
        return;
    }
    // Trim the namespace.
    String namespaceTrimmed = namespace.trim();
    // Check if the current user is authorized to the given namespace and has the given permissions.
    ApplicationUser applicationUser = getApplicationUser();
    if (!isAuthorized(applicationUser, namespaceTrimmed, permissions)) {
        String permissionsString = Arrays.asList(permissions).stream().map(n -> n.toString()).collect(Collectors.joining(" OR "));
        permissionsString = "[" + permissionsString + "]";
        // The current user is not authorized to access the given namespace, so log a warning and throw an exception.
        LOGGER.warn(String.format("User does not have permission(s) to the namespace. %s namespace=\"%s\" permissions=\"%s\"", applicationUser, namespaceTrimmed, permissionsString));
        if (applicationUser != null) {
            throw new AccessDeniedException(String.format("User \"%s\" does not have \"%s\" permission(s) to the namespace \"%s\"", applicationUser.getUserId(), permissionsString, namespaceTrimmed));
        } else {
            throw new AccessDeniedException(String.format("Current user does not have \"%s\" permission(s) to the namespace \"%s\"", permissionsString, namespaceTrimmed));
        }
    }
}
Also used : ApplicationUser(org.finra.herd.model.dto.ApplicationUser) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) NamespacePermissionEnum(org.finra.herd.model.api.xml.NamespacePermissionEnum) NamespaceAuthorization(org.finra.herd.model.api.xml.NamespaceAuthorization) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) ApplicationUser(org.finra.herd.model.dto.ApplicationUser) AccessDeniedException(org.springframework.security.access.AccessDeniedException) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) Component(org.springframework.stereotype.Component) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Collections(java.util.Collections) AccessDeniedException(org.springframework.security.access.AccessDeniedException)

Example 63 with StringUtils.isBlank

use of org.apache.commons.lang3.StringUtils.isBlank in project eol-globi-data by jhpoelen.

the class TaxonCacheService method initTaxonCache.

private void initTaxonCache() throws PropertyEnricherException {
    DB db = initDb("taxonCache");
    String taxonCacheName = "taxonCacheById";
    if (db.exists(taxonCacheName)) {
        LOG.info("re-using pre-existing cache");
        resolvedIdToTaxonMap = db.getTreeMap(taxonCacheName);
    } else {
        LOG.info("no pre-existing cache found, rebuilding...");
        LOG.info("taxon cache loading [" + taxonCacheResource + "]...");
        StopWatch watch = new StopWatch();
        watch.start();
        try {
            resolvedIdToTaxonMap = db.createTreeMap(taxonCacheName).pumpPresort(100000).pumpIgnoreDuplicates().pumpSource(taxonCacheIterator(taxonCacheResource, new LineSkipper() {

                @Override
                public boolean shouldSkipLine(LabeledCSVParser parser) {
                    final Taxon taxon = TaxonCacheParser.parseLine(parser);
                    return StringUtils.isBlank(taxon.getPath());
                }
            })).keySerializer(BTreeKeySerializer.STRING).make();
        } catch (IOException e) {
            throw new PropertyEnricherException("failed to instantiate taxonCache: [" + e.getMessage() + "]", e);
        }
        watch.stop();
        LOG.info("taxon cache loading [" + taxonCacheResource + "] done.");
        logCacheLoadStats(watch.getTime(), resolvedIdToTaxonMap.size());
        watch.reset();
    }
}
Also used : PropertyEnricherException(org.eol.globi.service.PropertyEnricherException) Taxon(org.eol.globi.domain.Taxon) LabeledCSVParser(com.Ostermiller.util.LabeledCSVParser) IOException(java.io.IOException) DB(org.mapdb.DB) StopWatch(org.apache.commons.lang3.time.StopWatch)

Example 64 with StringUtils.isBlank

use of org.apache.commons.lang3.StringUtils.isBlank in project eol-globi-data by jhpoelen.

the class CitationUtil method getDOI.

public static String getDOI(Dataset dataset) {
    String doi = dataset.getOrDefault("doi", "");
    URI archiveURI = dataset.getArchiveURI();
    if (StringUtils.isBlank(doi)) {
        String recordZenodo = StringUtils.replace(archiveURI.toString(), ZENODO_URL_PREFIX, "");
        String[] split = recordZenodo.split("/");
        if (split.length > 0) {
            doi = "https://doi.org/10.5281/zenodo." + split[0];
        }
    }
    return doi;
}
Also used : StringUtils.defaultString(org.apache.commons.lang3.StringUtils.defaultString) URI(java.net.URI)

Example 65 with StringUtils.isBlank

use of org.apache.commons.lang3.StringUtils.isBlank in project drbookings by DrBookings.

the class StatsViewController method updateUI.

private void updateUI(final BookingsByOrigin<BookingEntry> bookings, final Range<LocalDate> dateRange) {
    if (logger.isDebugEnabled()) {
        logger.debug("Statistics for\n" + BookingEntries.toBookings(bookings.getAllBookings()).stream().map(i -> i.toString()).collect(Collectors.joining("\n")));
    }
    final float allAllNigths = BookingEntries.countNights(bookings, false);
    final NavigableSet<LocalDate> allDates = bookings.getAllBookings(true).stream().map(b -> b.getDate()).collect(Collectors.toCollection(TreeSet::new));
    long monthCount = TemporalQueries.countOccurrences(allDates, SettingsManager.getInstance().getFixCostsPaymentDay());
    if (logger.isDebugEnabled()) {
        logger.debug("Month count: " + monthCount);
    }
    if (monthCount < 1) {
        monthCount = 1;
        if (logger.isDebugEnabled()) {
            logger.debug("Month count (corrected): " + monthCount);
        }
    }
    final float additionalCosts = SettingsManager.getInstance().getAdditionalCosts() * monthCount;
    final float numberOfRooms = SettingsManager.getInstance().getNumberOfRooms();
    final float totalAdditionalCosts = additionalCosts * numberOfRooms;
    if (logger.isDebugEnabled()) {
        logger.debug("Fix costs total: " + totalAdditionalCosts);
    }
    for (final Entry<BookingOrigin, Collection<BookingEntry>> e : bookings.getMap().entrySet()) {
        final Collection<? extends BookingEntry> bookingsFilteredByPaymentDate = e.getValue().stream().filter(new PaymentDateFilter(dateRange)).collect(Collectors.toList());
        final Collection<? extends BookingEntry> bookingsFilteredByCleaningDate = e.getValue().stream().filter(new CleaningDateFilter(dateRange)).collect(Collectors.toList());
        final int numberOfAllBookings = (int) BookingEntries.countBookings(new BookingsByOrigin<>(e.getValue()), false);
        final int numberOfPayedBookings = (int) BookingEntries.countBookings(new BookingsByOrigin<>(e.getValue()), false);
        final int numberOfAllNights = (int) BookingEntries.countNights(new BookingsByOrigin<>(e.getValue()), false);
        final int numberOfPayedNights = (int) BookingEntries.countNights(new BookingsByOrigin<>(bookingsFilteredByPaymentDate), false);
        final float percentage;
        if (StringUtils.isBlank(e.getKey().getName())) {
            percentage = 0;
        } else {
            percentage = numberOfAllNights / allAllNigths * 100f;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " percentage of all nights: " + percentage);
        }
        final double relativeFixCosts = totalAdditionalCosts * percentage / 100;
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " relative fix costs " + relativeFixCosts);
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + " number of bookings (all/payed): " + numberOfAllBookings + "/" + numberOfPayedBookings);
        }
        if (logger.isDebugEnabled()) {
            logger.debug(e.getKey() + ": Number of nights (all/payed): " + numberOfAllNights + "/" + numberOfPayedNights);
        }
        if (logger.isDebugEnabled()) {
            Set<Guest> set = e.getValue().stream().map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(LinkedHashSet::new));
            List<Guest> list = e.getValue().stream().filter(b -> !b.isCheckOut()).map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(ArrayList::new));
            StringBuilder sb = new StringBuilder(e.getKey() + " guest and nights (all):");
            int cnt = 1;
            int cnt2 = 0;
            for (final Guest guest : set) {
                final int cnt3 = Collections.frequency(list, guest);
                sb.append(String.format("%n%4d%20s%4d", cnt++, guest.getName(), cnt3));
                cnt2 += cnt3;
            }
            sb.append(String.format("%n%24s%4d", "Total", cnt2));
            logger.debug(sb.toString());
            set = bookingsFilteredByPaymentDate.stream().map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(LinkedHashSet::new));
            list = bookingsFilteredByPaymentDate.stream().filter(b -> !b.isCheckOut()).map(b -> b.getElement().getGuest()).collect(Collectors.toCollection(ArrayList::new));
            sb = new StringBuilder(e.getKey() + " guest and nights (payed):");
            cnt = 1;
            cnt2 = 0;
            for (final Guest guest : set) {
                final int cnt3 = Collections.frequency(list, guest);
                sb.append(String.format("%n%4d%20s%4d", cnt++, guest.getName(), cnt3));
                cnt2 += cnt3;
            }
            sb.append(String.format("%n%24s%4d", "Total", cnt2));
            logger.debug(sb.toString());
        }
        final StatisticsTableBean b = StatisticsTableBean.build(e.getKey().getName(), bookingsFilteredByPaymentDate);
        StatisticsTableBean.applyCleaningStuff(b, bookingsFilteredByCleaningDate);
        b.setFixCosts((float) relativeFixCosts);
        b.setNightsPercent(percentage);
        b.setNumberOfPayedNights(numberOfPayedNights);
        b.setNumberOfAllNights(numberOfAllNights);
        b.setNumberOfPayedBookings(numberOfPayedBookings);
        b.setNumberOfAllBookings(numberOfAllBookings);
        data.add(b);
    }
    // add a total row
    final float relativeFixCosts = totalAdditionalCosts;
    final StatisticsTableBean b = StatisticsTableBean.buildSum(data);
    b.setFixCosts(relativeFixCosts);
    b.setNightsPercent(100);
    data.add(b);
}
Also used : BookingSelectionManager(com.github.drbookings.ui.selection.BookingSelectionManager) Initializable(javafx.fxml.Initializable) java.util(java.util) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) IntegerCellValueFactory(com.github.drbookings.ui.IntegerCellValueFactory) FXCollections(javafx.collections.FXCollections) MainManager(com.github.drbookings.model.data.manager.MainManager) StringUtils(org.apache.commons.lang3.StringUtils) BookingsByOrigin(com.github.drbookings.ui.BookingsByOrigin) TableColumn(javafx.scene.control.TableColumn) BookingEntries(com.github.drbookings.model.data.BookingEntries) ListChangeListener(javafx.collections.ListChangeListener) Guest(com.github.drbookings.model.data.Guest) TableView(javafx.scene.control.TableView) Logger(org.slf4j.Logger) Range(com.google.common.collect.Range) CurrencyCellValueFactory(com.github.drbookings.ui.CurrencyCellValueFactory) Collectors(java.util.stream.Collectors) SettingsManager(com.github.drbookings.model.settings.SettingsManager) FXML(javafx.fxml.FXML) com.github.drbookings(com.github.drbookings) BookingOrigin(com.github.drbookings.model.data.BookingOrigin) StatisticsTableBean(com.github.drbookings.ui.beans.StatisticsTableBean) LocalDate(java.time.LocalDate) Entry(java.util.Map.Entry) ObservableList(javafx.collections.ObservableList) BookingEntry(com.github.drbookings.ui.BookingEntry) StatisticsTableBean(com.github.drbookings.ui.beans.StatisticsTableBean) Guest(com.github.drbookings.model.data.Guest) BookingsByOrigin(com.github.drbookings.ui.BookingsByOrigin) LocalDate(java.time.LocalDate) BookingOrigin(com.github.drbookings.model.data.BookingOrigin)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)54 List (java.util.List)33 Collectors (java.util.stream.Collectors)29 Map (java.util.Map)28 Set (java.util.Set)27 ArrayList (java.util.ArrayList)23 Optional (java.util.Optional)22 Collections (java.util.Collections)19 Logger (org.slf4j.Logger)19 LoggerFactory (org.slf4j.LoggerFactory)19 IOException (java.io.IOException)18 HashSet (java.util.HashSet)18 Collection (java.util.Collection)16 HashMap (java.util.HashMap)16 StopWatch (org.apache.commons.lang3.time.StopWatch)13 Autowired (org.springframework.beans.factory.annotation.Autowired)11 Slf4j (lombok.extern.slf4j.Slf4j)10 InputStream (java.io.InputStream)9 Inject (javax.inject.Inject)8 RegisteredTemplate (com.thinkbiganalytics.feedmgr.rest.model.RegisteredTemplate)7