Search in sources :

Example 11 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project coprhd-controller by CoprHD.

the class TextUtils method formatCSV.

/**
 * Formats some values into comma-separated text.
 *
 * @param values
 *            the values to format.
 * @return the CSV text.
 */
public static String formatCSV(Iterable<String> values) {
    StrBuilder sb = new StrBuilder();
    for (String value : values) {
        sb.appendSeparator(",");
        sb.append("\"");
        if (StringUtils.isNotEmpty(value)) {
            for (int i = 0; i < value.length(); i++) {
                char ch = value.charAt(i);
                if (ch == '"') {
                    sb.append('"');
                }
                sb.append(ch);
            }
        }
        sb.append("\"");
    }
    return sb.toString();
}
Also used : StrBuilder(org.apache.commons.lang3.text.StrBuilder)

Example 12 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project pentaho-platform by pentaho.

the class PentahoWebContextFilter method getActiveThemeVar.

// region get Environment Variables
private String getActiveThemeVar(HttpServletRequest request) {
    IPentahoSession session = getSession();
    String activeTheme = (String) session.getAttribute("pentaho-user-theme");
    String ua = request.getHeader("User-Agent");
    // check if we're coming from a mobile device, if so, lock to system default (ruby)
    if (StringUtils.isNotEmpty(ua) && ua.matches(".*(?i)(iPad|iPod|iPhone|Android).*")) {
        activeTheme = PentahoSystem.getSystemSetting("default-theme", "ruby");
    }
    if (activeTheme == null) {
        IUserSettingService settingsService = getUserSettingsService();
        try {
            activeTheme = settingsService.getUserSetting("pentaho-user-theme", null).getSettingValue();
        } catch (Exception ignored) {
        // the user settings service is not valid in the agile-bi deployment of the server
        }
        if (activeTheme == null) {
            activeTheme = PentahoSystem.getSystemSetting("default-theme", "ruby");
        }
    }
    return activeTheme;
}
Also used : IUserSettingService(org.pentaho.platform.api.usersettings.IUserSettingService) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ServletException(javax.servlet.ServletException) ConcurrentException(org.apache.commons.lang3.concurrent.ConcurrentException) IOException(java.io.IOException)

Example 13 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project CzechIdMng by bcvsolutions.

the class IdentityAnonymousUsernameGenerator method generate.

@Override
public IdmIdentityDto generate(IdmIdentityDto dto, IdmGenerateValueDto valueGenerator) {
    Assert.notNull(dto, "DTO is required.");
    Assert.notNull(valueGenerator, "Value generator is required.");
    // if exists username and configuration doesn't allow regenerate return dto
    if (!valueGenerator.isRegenerateValue() && StringUtils.isNotEmpty(dto.getUsername())) {
        return dto;
    }
    // generator configuration
    int numPartLen = getNumberPartLength(valueGenerator);
    int numPartMax = calcMaxValueForLen(numPartLen);
    String prefix = getPrefixString(valueGenerator);
    // try to generate the new unique username within several attempts
    int attepts = GENERATE_ATTEMPTS;
    do {
        int randomPartVal = generateNumberPart(numPartMax);
        String username = createUsername(prefix, randomPartVal, numPartLen);
        // find at the first attempt OK
        if (!usernameInUse(username)) {
            dto.setUsername(username);
            return dto;
        }
    } while (--attepts != 0);
    // unsuccessful with random generation -> search for empty number slots
    String usernameRoot = createUsername(prefix, null, null);
    IdmIdentityFilter identityFilt = new IdmIdentityFilter();
    identityFilt.setText(usernameRoot);
    Page<IdmIdentityDto> page = null;
    int pageSize = SEARCH_PAGE_SIZE;
    int pageNum = 0;
    do {
        page = identityService.find(identityFilt, PageRequest.of(pageNum, pageSize, Sort.by(IdmIdentity_.username.getName()).ascending()));
        List<IdmIdentityDto> dtos = page.getContent();
        List<String> usernameNumbers = dtos.stream().map(IdmIdentityDto::getUsername).filter(usernameFilterFactory(usernameRoot, numPartLen)).map(name -> name.replace(usernameRoot, "")).collect(Collectors.toList());
        Integer newRandomPartVal = findEmptySlotFromRange(usernameNumbers, 0, usernameNumbers.size() - 1);
        if (newRandomPartVal != null) {
            String username = createUsername(prefix, newRandomPartVal, Integer.valueOf(numPartLen));
            dto.setUsername(username);
            return dto;
        }
        pageNum++;
    } while (pageNum < page.getTotalPages());
    // unable to find empty space by bisect? try min and max values which may still be missing
    // first index
    String username = createUsername(prefix, 0, numPartLen);
    if (!usernameInUse(username)) {
        dto.setUsername(username);
        return dto;
    }
    // last index
    username = createUsername(prefix, numPartMax, numPartLen);
    if (!usernameInUse(username)) {
        dto.setUsername(username);
        return dto;
    }
    // it's over nothing remains to try
    LOG.warn("The anonymous username generator reached the limit of the count of available numbers. Increase nuemric part length in the generator setting.");
    throw new ResultCodeException(CoreResultCode.IDENTITY_UNABLE_GENERATE_UNIQUE_USERNAME);
}
Also used : IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) Autowired(org.springframework.beans.factory.annotation.Autowired) Random(java.util.Random) StringUtils(org.apache.commons.lang3.StringUtils) PersistentType(eu.bcvsolutions.idm.core.eav.api.domain.PersistentType) BigDecimal(java.math.BigDecimal) IdmIdentityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Math(java.lang.Math) Sort(org.springframework.data.domain.Sort) AbstractValueGenerator(eu.bcvsolutions.idm.core.api.generator.AbstractValueGenerator) Description(org.springframework.context.annotation.Description) Predicate(java.util.function.Predicate) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) PageRequest(org.springframework.data.domain.PageRequest) Page(org.springframework.data.domain.Page) Collectors(java.util.stream.Collectors) List(java.util.List) Component(org.springframework.stereotype.Component) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) IdmIdentity_(eu.bcvsolutions.idm.core.model.entity.IdmIdentity_) Pattern(java.util.regex.Pattern) IdmIdentityService(eu.bcvsolutions.idm.core.api.service.IdmIdentityService) IdmGenerateValueDto(eu.bcvsolutions.idm.core.api.dto.IdmGenerateValueDto) Assert(org.springframework.util.Assert) IdmIdentityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmIdentityFilter) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)

Example 14 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project CzechIdMng by bcvsolutions.

the class LogbackLoggerManager method init.

@PostConstruct
public void init() {
    LOG.info("Initialize logger levels from configuration");
    // 
    loadFileLevels();
    // 
    // init from database
    Map<String, String> initPackageLevels = Maps.newHashMap();
    configurationService.getConfigurations(PROPERTY_PREFIX).values().stream().filter(configuration -> {
        return getPackageName(configuration.getName()) != null;
    }).filter(configuration -> {
        return StringUtils.isNotEmpty(configuration.getValue());
    }).forEach(configuration -> {
        initPackageLevels.put(getPackageName(configuration.getName()), configuration.getValue());
    });
    // 
    // init from application files
    configurationService.getAllConfigurationsFromFiles().stream().filter(configuration -> {
        return getPackageName(configuration.getName()) != null;
    }).filter(configuration -> {
        return StringUtils.isNotEmpty(configuration.getValue());
    }).filter(configuration -> {
        return !initPackageLevels.containsKey(getPackageName(configuration.getName()));
    }).forEach(configuration -> {
        initPackageLevels.put(getPackageName(configuration.getName()), configuration.getValue());
    });
    // 
    initPackageLevels.forEach((packageName, level) -> {
        Level originalLevel = setLoggerLevel(packageName, Level.toLevel(level));
        if (!originalLevelCache.containsKey(packageName)) {
            originalLevelCache.put(packageName, originalLevel);
        }
    });
}
Also used : LoggerManager(eu.bcvsolutions.idm.core.api.service.LoggerManager) ConfigurationDeleteLoggerProcessor(eu.bcvsolutions.idm.core.model.event.processor.configuration.ConfigurationDeleteLoggerProcessor) ConfigurationSaveLoggerProcessor(eu.bcvsolutions.idm.core.model.event.processor.configuration.ConfigurationSaveLoggerProcessor) ImmutableMap(com.google.common.collect.ImmutableMap) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) IdmConfigurationDto(eu.bcvsolutions.idm.core.api.dto.IdmConfigurationDto) ConfigurationService(eu.bcvsolutions.idm.core.api.service.ConfigurationService) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) Maps(com.google.common.collect.Maps) LoggerContext(ch.qos.logback.classic.LoggerContext) List(java.util.List) Level(ch.qos.logback.classic.Level) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) Logger(ch.qos.logback.classic.Logger) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Map(java.util.Map) PostConstruct(javax.annotation.PostConstruct) CodeableComparator(eu.bcvsolutions.idm.core.api.domain.comparator.CodeableComparator) Assert(org.springframework.util.Assert) Level(ch.qos.logback.classic.Level) PostConstruct(javax.annotation.PostConstruct)

Example 15 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project CzechIdMng by bcvsolutions.

the class DefaultIdmScriptServiceIntegrationTest method testDeployScriptFromAttachement.

@Test
public void testDeployScriptFromAttachement() throws IOException {
    String scriptCode = getHelper().createName();
    String scriptOne = "<script> <code>" + scriptCode + "</code> <name>Test script 1</name> <body> <![CDATA[ String s; ]]> </body> <type>groovy</type> <category>DEFAULT</category> <parameters>test1</parameters> <services> <service> <name>treeNodeService</name> <className>eu.bcvsolutions.idm.core.model.service.impl.DefaultIdmTreeNodeService</className> </service> <service> <name>identityService</name> <className>eu.bcvsolutions.idm.core.model.service.impl.DefaultIdmIdentityService</className> </service> </services><allowClasses> <allowClass> <className>eu.bcvsolutions.idm.core.model.entity.IdmTreeNode</className> </allowClass> <allowClass> <className>eu.bcvsolutions.idm.core.model.entity.IdmIdentity</className> </allowClass> </allowClasses> </script>";
    // create attachment
    IdmAttachmentDto attachment = new IdmAttachmentDto();
    attachment.setOwnerType(AttachmentManager.TEMPORARY_ATTACHMENT_OWNER_TYPE);
    attachment.setName("scriptOne.xml");
    attachment.setMimetype(MediaType.TEXT_XML_VALUE);
    attachment.setInputData(IOUtils.toInputStream(scriptOne));
    // owner and version is resolved after attachment is saved
    attachment = attachmentManager.saveAttachment(null, attachment);
    // deploy
    List<IdmScriptDto> results = scriptService.deploy(attachment);
    // 
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(scriptCode, results.get(0).getCode());
    // 
    // test authorities
    IdmScriptAuthorityFilter authorityFilter = new IdmScriptAuthorityFilter();
    authorityFilter.setScriptId(results.get(0).getId());
    List<IdmScriptAuthorityDto> authorities = scriptAuthorityService.find(authorityFilter, null).getContent();
    Assert.assertEquals(4, authorities.size());
    Assert.assertTrue(authorities.stream().allMatch(a -> StringUtils.isNotEmpty(a.getClassName())));
    Assert.assertTrue(authorities.stream().anyMatch(a -> "treeNodeService".equals(a.getService())));
    Assert.assertTrue(authorities.stream().anyMatch(a -> "identityService".equals(a.getService())));
    Assert.assertTrue(authorities.stream().anyMatch(a -> a.getClassName().equals("eu.bcvsolutions.idm.core.model.entity.IdmTreeNode")));
    Assert.assertTrue(authorities.stream().anyMatch(a -> a.getClassName().equals("eu.bcvsolutions.idm.core.model.entity.IdmIdentity")));
    // 
    // deploy from archive
    IdmScriptDto scriptOneDto = scriptService.getByCode(scriptCode);
    String scriptCodeTwo = getHelper().createName();
    String scriptOneUpdateName = getHelper().createName();
    scriptOne = "<script> <code>" + scriptCode + "</code> <name>" + scriptOneUpdateName + "</name> <body> <![CDATA[ String s; ]]> </body> <type>groovy</type> <category>DEFAULT</category> <parameters>test1</parameters> <services> <service> <name>treeNodeService</name> <className>eu.bcvsolutions.idm.core.model.service.impl.DefaultIdmTreeNodeService</className> </service> </services><allowClasses> <allowClass> <className>eu.bcvsolutions.idm.core.model.entity.IdmTreeNode</className> </allowClass> <allowClass> <className>eu.bcvsolutions.idm.core.model.entity.IdmIdentity</className> </allowClass> </allowClasses> </script>";
    // create attachment
    String scriptTwo = "<script> <code>" + scriptCodeTwo + "</code> <name>Test script 2</name> <body> <![CDATA[ String s; ]]> </body> <type>groovy</type> <category>DEFAULT</category> <parameters>test1</parameters> <services> <service> <name>treeNodeService</name> <className>eu.bcvsolutions.idm.core.model.service.impl.DefaultIdmTreeNodeService</className> </service> <service> <name>identityService</name> <className>eu.bcvsolutions.idm.core.model.service.impl.DefaultIdmIdentityService</className> </service> </services><allowClasses> <allowClass> <className>eu.bcvsolutions.idm.core.model.entity.IdmTreeNode</className> </allowClass> <allowClass> <className>eu.bcvsolutions.idm.core.model.entity.IdmIdentity</className> </allowClass> </allowClasses> </script>";
    IdmAttachmentDto attachmentOne = new IdmAttachmentDto();
    attachmentOne.setOwnerType(AttachmentManager.TEMPORARY_ATTACHMENT_OWNER_TYPE);
    attachmentOne.setName("scriptOne.xml");
    attachmentOne.setMimetype(MediaType.TEXT_XML_VALUE);
    attachmentOne.setInputData(IOUtils.toInputStream(scriptOne));
    attachmentOne = attachmentManager.saveAttachment(null, attachmentOne);
    IdmAttachmentDto attachmentTwo = new IdmAttachmentDto();
    attachmentTwo.setOwnerType(AttachmentManager.TEMPORARY_ATTACHMENT_OWNER_TYPE);
    attachmentTwo.setName("scriptTwo.xml");
    attachmentTwo.setMimetype(MediaType.TEXT_XML_VALUE);
    attachmentTwo.setInputData(IOUtils.toInputStream(scriptTwo));
    attachmentTwo = attachmentManager.saveAttachment(null, attachmentTwo);
    // zip
    File zipFolder = attachmentManager.createTempDirectory(null).toFile();
    File targetFileOne = new File(zipFolder.toString(), String.format("%s.xml", attachmentOne.getName()));
    Files.copy(attachmentManager.getAttachmentData(attachmentOne.getId()), targetFileOne.toPath(), StandardCopyOption.REPLACE_EXISTING);
    File targetFileTwo = new File(zipFolder.toString(), String.format("%s.xml", attachmentTwo.getName()));
    Files.copy(attachmentManager.getAttachmentData(attachmentTwo.getId()), targetFileTwo.toPath(), StandardCopyOption.REPLACE_EXISTING);
    // compress
    File zipFile = attachmentManager.createTempFile();
    ZipUtils.compress(zipFolder, zipFile.getPath());
    IdmAttachmentDto attachmentZip = new IdmAttachmentDto();
    attachmentZip.setOwnerType(AttachmentManager.TEMPORARY_ATTACHMENT_OWNER_TYPE);
    attachmentZip.setInputData(new FileInputStream(zipFile));
    attachmentZip.setEncoding(AttachableEntity.DEFAULT_ENCODING);
    // zip ~ octet stream
    attachmentZip.setMimetype(AttachableEntity.DEFAULT_MIMETYPE);
    attachmentZip.setName("backup.zip");
    attachmentZip = attachmentManager.saveAttachment(null, attachmentZip);
    // deploy
    results = scriptService.deploy(attachmentZip);
    // 
    Assert.assertEquals(2, results.size());
    Assert.assertTrue(results.stream().anyMatch(s -> s.getId().equals(scriptOneDto.getId())));
    Assert.assertTrue(results.stream().anyMatch(s -> s.getCode().equals(scriptCode) && s.getName().equals(scriptOneUpdateName)));
    Assert.assertTrue(results.stream().anyMatch(s -> s.getCode().equals(scriptCodeTwo)));
    // 
    // test authorities
    authorityFilter = new IdmScriptAuthorityFilter();
    authorityFilter.setScriptId(scriptOneDto.getId());
    authorities = scriptAuthorityService.find(authorityFilter, null).getContent();
    Assert.assertEquals(3, authorities.size());
    Assert.assertTrue(authorities.stream().allMatch(a -> StringUtils.isNotEmpty(a.getClassName())));
    Assert.assertTrue(authorities.stream().anyMatch(a -> "treeNodeService".equals(a.getService())));
    Assert.assertTrue(authorities.stream().anyMatch(a -> a.getClassName().equals("eu.bcvsolutions.idm.core.model.entity.IdmTreeNode")));
    Assert.assertTrue(authorities.stream().anyMatch(a -> a.getClassName().equals("eu.bcvsolutions.idm.core.model.entity.IdmIdentity")));
    // 
    authorityFilter = new IdmScriptAuthorityFilter();
    authorityFilter.setScriptId(scriptService.getByCode(scriptCodeTwo).getId());
    authorities = scriptAuthorityService.find(authorityFilter, null).getContent();
    Assert.assertEquals(4, authorities.size());
    Assert.assertTrue(authorities.stream().allMatch(a -> StringUtils.isNotEmpty(a.getClassName())));
    Assert.assertTrue(authorities.stream().anyMatch(a -> "treeNodeService".equals(a.getService())));
    Assert.assertTrue(authorities.stream().anyMatch(a -> "identityService".equals(a.getService())));
    Assert.assertTrue(authorities.stream().anyMatch(a -> a.getClassName().equals("eu.bcvsolutions.idm.core.model.entity.IdmTreeNode")));
    Assert.assertTrue(authorities.stream().anyMatch(a -> a.getClassName().equals("eu.bcvsolutions.idm.core.model.entity.IdmIdentity")));
}
Also used : IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) IdmScriptCategory(eu.bcvsolutions.idm.core.api.domain.IdmScriptCategory) IdmScriptAuthorityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmScriptAuthorityFilter) IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) AttachableEntity(eu.bcvsolutions.idm.core.ecm.api.entity.AttachableEntity) ZonedDateTime(java.time.ZonedDateTime) Recoverable(eu.bcvsolutions.idm.core.api.service.Recoverable) Autowired(org.springframework.beans.factory.annotation.Autowired) ConfigurationService(eu.bcvsolutions.idm.core.api.service.ConfigurationService) StringUtils(org.apache.commons.lang3.StringUtils) StandardCopyOption(java.nio.file.StandardCopyOption) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) After(org.junit.After) AbstractIntegrationTest(eu.bcvsolutions.idm.test.api.AbstractIntegrationTest) Assert.fail(org.junit.Assert.fail) Before(org.junit.Before) IdmScriptAuthorityDto(eu.bcvsolutions.idm.core.api.dto.IdmScriptAuthorityDto) Files(java.nio.file.Files) Assert.assertNotNull(org.junit.Assert.assertNotNull) AttachmentManager(eu.bcvsolutions.idm.core.ecm.api.service.AttachmentManager) MediaType(org.springframework.http.MediaType) DecimalFormat(java.text.DecimalFormat) Assert.assertTrue(org.junit.Assert.assertTrue) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Test(org.junit.Test) FileInputStream(java.io.FileInputStream) ApplicationContext(org.springframework.context.ApplicationContext) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) IdmScriptDto(eu.bcvsolutions.idm.core.api.dto.IdmScriptDto) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) Assert.assertNull(org.junit.Assert.assertNull) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) ZipUtils(eu.bcvsolutions.idm.core.api.utils.ZipUtils) Assert(org.junit.Assert) IdmScriptAuthorityService(eu.bcvsolutions.idm.core.api.service.IdmScriptAuthorityService) Assert.assertEquals(org.junit.Assert.assertEquals) Transactional(org.springframework.transaction.annotation.Transactional) IdmScriptAuthorityDto(eu.bcvsolutions.idm.core.api.dto.IdmScriptAuthorityDto) IdmScriptDto(eu.bcvsolutions.idm.core.api.dto.IdmScriptDto) IdmScriptAuthorityFilter(eu.bcvsolutions.idm.core.api.dto.filter.IdmScriptAuthorityFilter) File(java.io.File) FileInputStream(java.io.FileInputStream) AbstractIntegrationTest(eu.bcvsolutions.idm.test.api.AbstractIntegrationTest) Test(org.junit.Test)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)42 List (java.util.List)31 Map (java.util.Map)28 Collectors (java.util.stream.Collectors)21 ArrayList (java.util.ArrayList)20 HashMap (java.util.HashMap)19 IOException (java.io.IOException)17 LoggerFactory (org.slf4j.LoggerFactory)15 Set (java.util.Set)14 Autowired (org.springframework.beans.factory.annotation.Autowired)14 Logger (org.slf4j.Logger)13 Collections (java.util.Collections)12 HashSet (java.util.HashSet)12 Optional (java.util.Optional)12 Arrays (java.util.Arrays)11 File (java.io.File)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)7 java.util (java.util)7 Collection (java.util.Collection)7 Pattern (java.util.regex.Pattern)7