Search in sources :

Example 16 with StringUtils.isNotEmpty

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

the class DefaultFormService method validateAttribute.

private InvalidFormAttributeDto validateAttribute(IdmFormDefinitionDto formDefinition, IdmFormAttributeDto formAttribute, List<IdmFormValueDto> formValues, boolean validateOnlySameOwnerType) {
    Assert.notNull(formAttribute, "Form attribute is required.");
    // 
    InvalidFormAttributeDto result = new InvalidFormAttributeDto(formAttribute);
    result.setDefinitionCode(formDefinition.getCode());
    // 
    if (formAttribute.isRequired()) {
        if (CollectionUtils.isEmpty(formValues) || !formValues.stream().filter(formValue -> !formValue.isEmpty()).findFirst().isPresent()) {
            LOG.debug("Form attribute [{}] validation failed - value is required.", formAttribute.getCode());
            // 
            result.setMissingValue(true);
        }
    }
    if (CollectionUtils.isEmpty(formValues)) {
        // values are not filled => other validations is not needed.
        return result;
    }
    // TODO: redesign to registrable validators
    // TODO: multiple values -> the last validation error is returned. Return invalid attribute for the all values ...
    formValues.stream().filter(formValue -> !formValue.isEmpty()).forEach(formValue -> {
        // minimum value validation
        if (formAttribute.getMin() != null) {
            if (formAttribute.getPersistentType() == PersistentType.SHORTTEXT) {
                String value = formValue.getShortTextValue();
                if (value.length() < formAttribute.getMin().intValue()) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is shorter than min [{}].", formAttribute.getCode(), value.length(), formAttribute.getMin());
                    // 
                    result.setMinValue(formAttribute.getMin());
                }
            } else if (formAttribute.getPersistentType() == PersistentType.TEXT) {
                String value = formValue.getStringValue();
                if (value.length() < formAttribute.getMin().intValue()) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is shorter than min [{}].", formAttribute.getCode(), value.length(), formAttribute.getMin());
                    // 
                    result.setMinValue(formAttribute.getMin());
                }
            } else if (formAttribute.getPersistentType() == PersistentType.DATE) {
                LocalDate value = formValue.getDateValue().toLocalDate();
                if (value.isBefore(LocalDate.now().plusDays(formAttribute.getMin().longValue()))) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is before than [{}] days.", formAttribute.getCode(), value, formAttribute.getMin());
                    // 
                    result.setMinValue(formAttribute.getMin());
                }
            } else if (formAttribute.getPersistentType() == PersistentType.DATETIME) {
                ZonedDateTime value = formValue.getDateValue();
                if (value.isBefore(ZonedDateTime.now().plusDays(formAttribute.getMin().longValue()))) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is before than [{}] days.", formAttribute.getCode(), value, formAttribute.getMin());
                    // 
                    result.setMinValue(formAttribute.getMin());
                }
            } else {
                if (formValue.getLongValue() != null && formAttribute.getMin().compareTo(BigDecimal.valueOf(formValue.getLongValue())) > 0) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is lesser than min [{}].", formAttribute.getCode(), formValue.getLongValue(), formAttribute.getMin());
                    // 
                    result.setMinValue(formAttribute.getMin());
                }
                if (formValue.getDoubleValue() != null && formAttribute.getMin().compareTo(formValue.getDoubleValue()) > 0) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is lesser than min [{}].", formAttribute.getCode(), formValue.getDoubleValue(), formAttribute.getMin());
                    // 
                    result.setMinValue(formAttribute.getMin());
                }
            }
        }
        // maximum value validation
        if (formAttribute.getMax() != null) {
            if (formAttribute.getPersistentType() == PersistentType.SHORTTEXT) {
                String value = formValue.getShortTextValue();
                if (value.length() > formAttribute.getMax().intValue()) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is shorter than min [{}].", formAttribute.getCode(), value.length(), formAttribute.getMax());
                    // 
                    result.setMaxValue(formAttribute.getMax());
                }
            } else if (formAttribute.getPersistentType() == PersistentType.TEXT) {
                String value = formValue.getStringValue();
                if (value.length() > formAttribute.getMax().intValue()) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is greater than min [{}].", formAttribute.getCode(), value.length(), formAttribute.getMax());
                    // 
                    result.setMaxValue(formAttribute.getMax());
                }
            } else if (formAttribute.getPersistentType() == PersistentType.DATE) {
                LocalDate value = formValue.getDateValue().toLocalDate();
                if (value.isAfter(LocalDate.now().plusDays(formAttribute.getMax().longValue()))) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is after than [{}] days.", formAttribute.getCode(), value, formAttribute.getMax());
                    // 
                    result.setMaxValue(formAttribute.getMax());
                }
            } else if (formAttribute.getPersistentType() == PersistentType.DATETIME) {
                ZonedDateTime value = formValue.getDateValue();
                if (value.isAfter(ZonedDateTime.now().plusDays(formAttribute.getMax().longValue()))) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is after than [{}] days.", formAttribute.getCode(), value, formAttribute.getMax());
                    // 
                    result.setMaxValue(formAttribute.getMax());
                }
            } else {
                if (formValue.getLongValue() != null && formAttribute.getMax().compareTo(BigDecimal.valueOf(formValue.getLongValue())) < 0) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is greater than max [{}].", formAttribute.getCode(), formValue.getLongValue(), formAttribute.getMax());
                    // 
                    result.setMaxValue(formAttribute.getMax());
                }
                if (formValue.getDoubleValue() != null && formAttribute.getMax().compareTo(formValue.getDoubleValue()) < 0) {
                    LOG.debug("Form attribute [{}] validation failed - given value [{}] is greater than max [{}].", formAttribute.getCode(), formValue.getDoubleValue(), formAttribute.getMax());
                    // 
                    result.setMaxValue(formAttribute.getMax());
                }
            }
        }
        String regex = formAttribute.getRegex();
        if (StringUtils.isNotEmpty(regex)) {
            Pattern p = Pattern.compile(regex);
            String stringValue = formValue.getValue().toString();
            // all persistent types are supported on BE, but string values makes the good sense.
            Matcher m = p.matcher(stringValue);
            if (!m.matches()) {
                LOG.debug("Form attribute [{}] validation failed - given value [{}] does not match regex [{}].", formAttribute.getCode(), stringValue, regex);
                // 
                result.setRegexValue(regex);
            }
        }
        if (formAttribute.isUnique()) {
            IdmFormValueFilter<FormableEntity> valueFilter = new IdmFormValueFilter<>();
            valueFilter.setAttributeId(formValue.getFormAttribute());
            valueFilter.setPersistentType(formValue.getPersistentType());
            valueFilter.setStringValue(formValue.getStringValue());
            valueFilter.setShortTextValue(formValue.getShortTextValue());
            valueFilter.setBooleanValue(formValue.getBooleanValue());
            valueFilter.setLongValue(formValue.getLongValue());
            valueFilter.setDoubleValue(formValue.getDoubleValue());
            valueFilter.setDateValue(formValue.getDateValue());
            valueFilter.setUuidValue(formValue.getUuidValue());
            // 
            Identifiable owner = getEmptyOwner(formDefinition);
            Assert.notNull(owner, "Filter - attribute owner is required. Is possible to filter form values by given owner only");
            // 
            FormValueService<FormableEntity> formValueService = getFormValueService(owner.getClass());
            // 
            List<IdmFormValueDto> existValues = formValueService.find(valueFilter, PageRequest.of(0, 2)).getContent();
            // 
            if (existValues.stream().filter(v -> {
                if (validateOnlySameOwnerType) {
                    return v.getOwnerType().equals(formValue.getOwnerType());
                }
                return true;
            }).anyMatch(v -> formValue.getId() == null || !formValue.getId().equals(v.getId()))) {
                LOG.debug("Form attribute [{}] validation failed - given value [{}] is not unigue.", formAttribute.getCode(), formValue.getValue());
                // 
                result.setUniqueValue(formValue.getValue().toString());
            }
        }
    });
    // 
    return result;
}
Also used : AbstractFormValue_(eu.bcvsolutions.idm.core.eav.entity.AbstractFormValue_) Order(org.springframework.data.domain.Sort.Order) DtoUtils(eu.bcvsolutions.idm.core.api.utils.DtoUtils) ZonedDateTime(java.time.ZonedDateTime) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) PluginRegistry(org.springframework.plugin.core.PluginRegistry) FormProjectionManager(eu.bcvsolutions.idm.core.eav.api.service.FormProjectionManager) Autowired(org.springframework.beans.factory.annotation.Autowired) FormDefinitionCache(eu.bcvsolutions.idm.core.eav.api.domain.FormDefinitionCache) FormService(eu.bcvsolutions.idm.core.eav.api.service.FormService) StringUtils(org.apache.commons.lang3.StringUtils) BigDecimal(java.math.BigDecimal) CoreEvent(eu.bcvsolutions.idm.core.api.event.CoreEvent) Matcher(java.util.regex.Matcher) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) Map(java.util.Map) BasePermission(eu.bcvsolutions.idm.core.security.api.domain.BasePermission) IdmFormAttributeService(eu.bcvsolutions.idm.core.eav.api.service.IdmFormAttributeService) Pageable(org.springframework.data.domain.Pageable) Sort(org.springframework.data.domain.Sort) FormableFilter(eu.bcvsolutions.idm.core.api.dto.filter.FormableFilter) Method(java.lang.reflect.Method) ImmutableMap(com.google.common.collect.ImmutableMap) ConfigurationClassProperty(eu.bcvsolutions.idm.core.api.domain.ConfigurationClassProperty) Set(java.util.Set) PageRequest(org.springframework.data.domain.PageRequest) UUID(java.util.UUID) IdmFormAttributeFilter(eu.bcvsolutions.idm.core.eav.api.dto.filter.IdmFormAttributeFilter) Page(org.springframework.data.domain.Page) Collectors(java.util.stream.Collectors) IntrospectionException(java.beans.IntrospectionException) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) List(java.util.List) PermissionUtils(eu.bcvsolutions.idm.core.security.api.utils.PermissionUtils) PropertyDescriptor(java.beans.PropertyDescriptor) LocalDate(java.time.LocalDate) Entry(java.util.Map.Entry) Identifiable(eu.bcvsolutions.idm.core.api.domain.Identifiable) Lazy(org.springframework.context.annotation.Lazy) Pattern(java.util.regex.Pattern) PageImpl(org.springframework.data.domain.PageImpl) FormableDto(eu.bcvsolutions.idm.core.api.dto.FormableDto) IdmFormAttribute_(eu.bcvsolutions.idm.core.eav.entity.IdmFormAttribute_) FormableEntity(eu.bcvsolutions.idm.core.eav.api.entity.FormableEntity) FormAttributeRendererDto(eu.bcvsolutions.idm.core.eav.api.dto.FormAttributeRendererDto) OrderAwarePluginRegistry(org.springframework.plugin.core.OrderAwarePluginRegistry) IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) HashMap(java.util.HashMap) ValueWrapper(eu.bcvsolutions.idm.core.api.config.cache.domain.ValueWrapper) MessageFormat(java.text.MessageFormat) ArrayList(java.util.ArrayList) PersistentType(eu.bcvsolutions.idm.core.eav.api.domain.PersistentType) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) IdmFormValueFilter(eu.bcvsolutions.idm.core.eav.api.dto.filter.IdmFormValueFilter) Introspector(java.beans.Introspector) IdmBasePermission(eu.bcvsolutions.idm.core.security.api.domain.IdmBasePermission) Lists(com.google.common.collect.Lists) LookupService(eu.bcvsolutions.idm.core.api.service.LookupService) CollectionUtils(org.apache.commons.collections.CollectionUtils) EntityUtils(eu.bcvsolutions.idm.core.api.utils.EntityUtils) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) IdmExportImportDto(eu.bcvsolutions.idm.core.api.dto.IdmExportImportDto) EntityEvent(eu.bcvsolutions.idm.core.api.event.EntityEvent) ConfigurationClass(eu.bcvsolutions.idm.core.api.domain.ConfigurationClass) IdmFormDefinition_(eu.bcvsolutions.idm.core.eav.entity.IdmFormDefinition_) FormAttributeRenderer(eu.bcvsolutions.idm.core.eav.api.service.FormAttributeRenderer) IdmFormDefinitionFilter(eu.bcvsolutions.idm.core.eav.api.dto.filter.IdmFormDefinitionFilter) CoreException(eu.bcvsolutions.idm.core.api.exception.CoreException) AttachmentManager(eu.bcvsolutions.idm.core.ecm.api.service.AttachmentManager) ObjectUtils(org.springframework.util.ObjectUtils) IdmCacheManager(eu.bcvsolutions.idm.core.api.service.IdmCacheManager) EnabledEvaluator(eu.bcvsolutions.idm.core.security.api.service.EnabledEvaluator) ApplicationContext(org.springframework.context.ApplicationContext) EventContext(eu.bcvsolutions.idm.core.api.event.EventContext) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) ExportDescriptorDto(eu.bcvsolutions.idm.core.api.dto.ExportDescriptorDto) CoreResultCode(eu.bcvsolutions.idm.core.api.domain.CoreResultCode) FormValueService(eu.bcvsolutions.idm.core.eav.api.service.FormValueService) IdmFormDefinitionService(eu.bcvsolutions.idm.core.eav.api.service.IdmFormDefinitionService) IdmForm(eu.bcvsolutions.idm.core.eav.entity.IdmForm) CoreEventType(eu.bcvsolutions.idm.core.api.event.CoreEvent.CoreEventType) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) Comparator(java.util.Comparator) EntityEventManager(eu.bcvsolutions.idm.core.api.service.EntityEventManager) Transactional(org.springframework.transaction.annotation.Transactional) Assert(org.springframework.util.Assert) FormDefinitionAttributes(eu.bcvsolutions.idm.core.eav.api.dto.FormDefinitionAttributes) InvalidFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.InvalidFormAttributeDto) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) LocalDate(java.time.LocalDate) FormableEntity(eu.bcvsolutions.idm.core.eav.api.entity.FormableEntity) Identifiable(eu.bcvsolutions.idm.core.api.domain.Identifiable) ZonedDateTime(java.time.ZonedDateTime) InvalidFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.InvalidFormAttributeDto) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto) IdmFormValueFilter(eu.bcvsolutions.idm.core.eav.api.dto.filter.IdmFormValueFilter)

Example 17 with StringUtils.isNotEmpty

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

the class ConsoleRunner method run.

@Override
public void run(String... args) throws ParseException, IOException {
    // 
    // available commands
    Option optionVersion = Option.builder("v").longOpt("version").desc("print tool version.").build();
    Option optionHelp = Option.builder("h").longOpt("help").desc("print this message.").build();
    Option optionBuild = Option.builder().longOpt("build").desc("Build project or build product only (under current develop version in develop branch).\n" + "Maven 'install' command is used for product build, artifact will be installed into the local maven repository (=> usable as dependency for other module).\n" + "Use '-p' argument to project build.").build();
    Option optionRelease = Option.builder().longOpt("release").desc("Release product or module under '--release-version' argument. New development version will be set as '--develop-version' argument.").build();
    Option optionPublish = Option.builder().longOpt("publish").desc("Push prepared development, production and tags into origin repository.").build();
    Option optionReleaseAndPublish = Option.builder().longOpt("release-publish").desc("Release and publish shortcut as one command, taking the same arguments as '--release' command.").build();
    Option optionGetVersion = Option.builder().longOpt("get-version").desc("Get current product version (on the development branch or set '--development-branch' argument).").build();
    Option optionSetVersion = Option.builder().longOpt("set-version").desc("Set current product version (on the development branch - development branch can be changed only).").build();
    Option optionRevertVersion = Option.builder().longOpt("revert-version").desc("Changed versions by release command can be reverted if needed (before commit, usable after change product version only).").build();
    // 
    // product root
    Option optionRepositoryLocation = Option.builder("r").longOpt("repository-location").desc("Repository root folder - should contain all modules (<repository-location>/Realization/...).\n" + "Folder 'CzechIdMng' in the same folder as idm-tool.jar will be used as default for product.\n" + "Folder '<module>' in the same folder as idm-tool.jar will be used as default for module.\n").argName("path").hasArg().build();
    // 
    // optional arguments
    Option optionMavenHome = Option.builder().required(false).longOpt("maven-home").desc("Maven home directory.\n" + "MAVEN_HOME system property will be used as default.\n" + "Maven directory should contain command <maven-home>/bin/mvn.").argName("path").hasArg().build();
    Option optionNodeHome = Option.builder().required(false).longOpt("node-home").desc("Node home directory.\n" + "Global node instalation directory should contain executable node command.\n" + "Node and npm will be dowloaded and installed localy automaticaly into tool target folder (<target>/npm) by default otherwise.\n" + "For Windows <node-home>/node/node.exe.\n" + "For Linux <node-home>/node").argName("path").hasArg().build();
    Option optionDevelopBranch = Option.builder().required(false).longOpt("develop-branch").desc("Branch with feature - working branch.\n" + "'develop' will be used as default.").argName("branchName").hasArg().build();
    Option optionMasterBranch = Option.builder().required(false).longOpt("master-branch").desc("Branch for releases - where feature has to be merged after release.\n" + "'master' will be used as default.\n" + "'none' can be given - merge don't be executed (e.g. when some old hotfix branch is released).\n").argName("masterBranch").hasArg().build();
    Option optionReleaseVersion = Option.builder().required(false).longOpt("release-version").desc("Usable with '--release' command. Release will be create under this version.\n" + "Stable semantic version will be used as default (=> current no snapshot version).").argName("version").hasArg().build();
    Option optionDevelopVersion = Option.builder().required(false).longOpt("develop-version").desc("Usable with '--release' command. After release this version will be used in development branch.\n" + "Next minor snapshot semantic version will be used as default (=> current minor snapshot version + 1).\n" + "See major, minor, patch, hotfix argument if different version is needed.").argName("snapshot version").hasArg().build();
    Option optionUsername = Option.builder().required(false).longOpt("username").desc("Git username, if https repitory is used. When ssh repository is used, then passphrase for ssh key is needed only.").argName("git username").hasArg().build();
    Option optionPassword = Option.builder().required(false).longOpt("password").desc("If ssh repository is used / cloned, then passphrase for ssh key is needed only.\n" + "If https repository is used / cloned, then git username and password is needed.\n" + "If two-factor authentication is enabled for <username>, " + "then token has to be given (see git documentation, how to generate authentication token for developers).\n" + "If ssh key is used, then put passphrase for ssh key (It loads the known hosts and private keys from their " + "default locations (identity, id_rsa and id_dsa) in the user .ssh directory.).").argName("git password / token / ssh passphrase").hasArg().build();
    // 
    // module switch
    Option optionModule = Option.builder("m").required(false).longOpt("module").desc("Switch to module release / build.").argName("moduleId").hasArg().build();
    // 
    // project switch
    Option optionProject = Option.builder("p").required(false).longOpt("project").desc("Switch to project build.").build();
    // 
    // force commit / changes is not checked
    Option optionForce = Option.builder().required(false).longOpt("force").desc(String.format("Count of files changed by release command will not be checked. Limit of changed files is [%s].", ReleaseManager.MAX_RELEASE_CHANGES)).build();
    // major / minor / patch / hotfix
    Option optionMajor = Option.builder().required(false).longOpt("major").desc("Next develop version will be major, e.g. release 1.2.3 => develop 2.0.0-SNAPSHOT.").build();
    Option optionMinor = Option.builder().required(false).longOpt("minor").desc("Next develop version will be minor, e.g. release 1.2.3 => develop 1.3.0-SNAPSHOT. Will be applied as default.").build();
    Option optionPatch = Option.builder().required(false).longOpt("patch").desc("Next develop version will be patch, e.g. release 1.2.3 => develop 1.2.4-SNAPSHOT.").build();
    Option optionHotfix = Option.builder().required(false).longOpt("hotfix").desc("Next develop version will be hotfix, e.g. release 1.2.3 => develop 1.2.3.1-SNAPSHOT.").build();
    Option optionClean = Option.builder("c").required(false).longOpt("clean").desc("Clean up dowloaded frontend libraries in node_modules.").build();
    Option optionResolveDependencies = Option.builder().required(false).longOpt("resolve-dependencies").desc("Third party module dependencies will be resolved automatically (not resolved by default), when project is built.\n" + "Dependencies will not be resolved and included in build, if feature is not enabled => \n" + "all module dependencies has to be installed manually (prepared ~ copied in 'modules' folder).\n" + "Parameter is available for build a project only.").build();
    Option optionSkipFrontendBuild = Option.builder().required(false).longOpt("skip-frontend-build").desc("Frontend build will be skipped - product provided frontend will be used for build distribution artifacts.\n" + "Parameter is available for build a project only.").build();
    Options options = new Options();
    // 
    // available commands
    OptionGroup commandGroup = new OptionGroup();
    commandGroup.setRequired(true);
    commandGroup.addOption(optionVersion);
    commandGroup.addOption(optionHelp);
    commandGroup.addOption(optionBuild);
    commandGroup.addOption(optionRelease);
    commandGroup.addOption(optionPublish);
    commandGroup.addOption(optionReleaseAndPublish);
    commandGroup.addOption(optionSetVersion);
    commandGroup.addOption(optionGetVersion);
    commandGroup.addOption(optionRevertVersion);
    options.addOptionGroup(commandGroup);
    // 
    options.addOption(optionRepositoryLocation);
    options.addOption(optionMavenHome);
    options.addOption(optionNodeHome);
    options.addOption(optionDevelopBranch);
    options.addOption(optionMasterBranch);
    options.addOption(optionReleaseVersion);
    options.addOption(optionDevelopVersion);
    options.addOption(optionUsername);
    options.addOption(optionPassword);
    options.addOption(optionModule);
    options.addOption(optionProject);
    options.addOption(optionForce);
    options.addOption(optionMajor);
    options.addOption(optionMinor);
    options.addOption(optionPatch);
    options.addOption(optionHotfix);
    options.addOption(optionClean);
    options.addOption(optionResolveDependencies);
    options.addOption(optionSkipFrontendBuild);
    // 
    // parse arguments
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine = parser.parse(options, args, false);
    // log given arguments (for bug report, without password value)
    List<String> arguments = Arrays.stream(commandLine.getOptions()).map(option -> {
        if (!option.hasArg()) {
            return option.getLongOpt();
        }
        return String.format("%s=%s", option.getLongOpt(), // prevent to print password into logs
        option.getLongOpt().equals(optionPassword.getLongOpt()) ? GuardedString.SECRED_PROXY_STRING : option.getValue());
    }).collect(Collectors.toList());
    LOG.info("Running tool with arguments {}.", arguments);
    // 
    boolean projectBuild = commandLine.hasOption(optionProject.getLongOpt());
    boolean releaseModule = commandLine.hasOption(optionModule.getLongOpt());
    // 
    if (productReleaseManager == null) {
        // Product manager will be inited by default
        // manager's methods are used by console runner
        productReleaseManager = new ProductReleaseManager();
    }
    if (releaseModule && !projectBuild && moduleReleaseManager == null) {
        moduleReleaseManager = new ModuleReleaseManager(commandLine.getOptionValue(optionModule.getLongOpt()));
    }
    // 
    if (commandLine.hasOption(optionVersion.getLongOpt())) {
        System.out.println(String.format("v%s", getVersion()));
        return;
    }
    // 
    if (commandLine.hasOption(optionHelp.getLongOpt())) {
        printHelp(options);
        return;
    }
    // 
    String rootFolder = null;
    if (commandLine.hasOption(optionRepositoryLocation.getLongOpt())) {
        rootFolder = commandLine.getOptionValue(optionRepositoryLocation.getLongOpt());
    }
    // 
    String mavenHome = null;
    if (commandLine.hasOption(optionMavenHome.getLongOpt())) {
        mavenHome = commandLine.getOptionValue(optionMavenHome.getLongOpt());
    }
    String nodeHome = null;
    if (commandLine.hasOption(optionNodeHome.getLongOpt())) {
        nodeHome = commandLine.getOptionValue(optionNodeHome.getLongOpt());
    }
    // 
    if (projectBuild) {
        if (!commandLine.hasOption(optionBuild.getLongOpt())) {
            throw new BuildException("Build a project is supported only.");
        }
        boolean clean = commandLine.hasOption(optionClean.getLongOpt());
        boolean resolveDependencies = commandLine.hasOption(optionResolveDependencies.getLongOpt());
        boolean skipFrontendBuild = commandLine.hasOption(optionSkipFrontendBuild.getLongOpt());
        // 
        if (projectManager == null) {
            projectManager = new ProjectManager();
            projectManager.setMavenHome(mavenHome);
            projectManager.setNodeHome(nodeHome);
            projectManager.setResolveDependencies(resolveDependencies);
            projectManager.setSkipFrontendBuild(skipFrontendBuild);
            projectManager.init();
        }
        // /tool folder by default => project is in parent folder.
        projectManager.build(rootFolder == null ? "../" : rootFolder, clean);
        // 
        LOG.info("Complete!");
        return;
    }
    // 
    // Release
    ReleaseManager releaseManager = getReleaseManager(releaseModule);
    releaseManager.setMavenHome(mavenHome);
    // 
    if (commandLine.hasOption(optionRepositoryLocation.getLongOpt())) {
        releaseManager.setRepositoryRoot(commandLine.getOptionValue(optionRepositoryLocation.getLongOpt()));
    }
    if (commandLine.hasOption(optionDevelopBranch.getLongOpt())) {
        releaseManager.setDevelopBranch(commandLine.getOptionValue(optionDevelopBranch.getLongOpt()));
        LOG.debug("Using develop branch [{}].", releaseManager.getDevelopBranch());
    }
    if (commandLine.hasOption(optionMasterBranch.getLongOpt())) {
        String masterBranch = commandLine.getOptionValue(optionMasterBranch.getLongOpt());
        if (masterBranch.equals("none")) {
            masterBranch = null;
        }
        releaseManager.setMasterBranch(masterBranch);
        LOG.debug("Using production branch [{}].", releaseManager.getMasterBranch());
    }
    if (commandLine.hasOption(optionUsername.getLongOpt())) {
        String username = commandLine.getOptionValue(optionUsername.getLongOpt());
        releaseManager.setUsername(username);
        LOG.debug("Using git username [{}].", username);
    }
    // 
    GuardedString password = null;
    if (commandLine.hasOption(optionPassword.getLongOpt())) {
        password = new GuardedString(commandLine.getOptionValue(optionPassword.getLongOpt()));
    } else {
        // get password from file
        String externalPassword = getProperty(PROPERTY_PASSWORD);
        if (StringUtils.isNotEmpty(externalPassword)) {
            password = new GuardedString(externalPassword);
        } else if (commandLine.hasOption(optionRelease.getLongOpt()) || commandLine.hasOption(optionReleaseAndPublish.getLongOpt())) {
            // prompt when publish / release-publish command is used
            // creates a console object
            Console cnsl = System.console();
            if (cnsl != null) {
                System.out.println(optionPassword.getDescription());
                char[] pwd = cnsl.readPassword(String.format("%s: ", optionPassword.getArgName()));
                if (pwd != null && pwd.length > 0) {
                    password = new GuardedString(new String(pwd));
                }
            }
        }
    }
    if (password != null) {
        releaseManager.setPassword(password);
        LOG.info(String.format("Password (%s) is given.", optionPassword.getArgName()));
    }
    // 
    if (commandLine.hasOption(optionForce.getLongOpt())) {
        releaseManager.setForce(true);
        LOG.debug("Force argument was given, count of files changed by release command will not be checked.");
    }
    // before run - check props is set
    releaseManager.init();
    // 
    if (commandLine.hasOption(optionBuild.getLongOpt())) {
        String currentVersion = releaseManager.build();
        // 
        LOG.info("Product version [{}] successfully built and installed into local maven repository.", currentVersion);
    } else if (commandLine.hasOption(optionRelease.getLongOpt()) || commandLine.hasOption(optionReleaseAndPublish.getLongOpt())) {
        String releaseVersion = commandLine.getOptionValue(optionReleaseVersion.getLongOpt());
        String developVersion = commandLine.getOptionValue(optionDevelopVersion.getLongOpt());
        // current [snapshot] develop version
        String currentVersion = releaseManager.getCurrentVersion(null);
        // 
        if (StringUtils.isEmpty(developVersion)) {
            // prepare next development version by major / minor / patch / hotfix switch
            ReleaseManager.VersionType versionType = null;
            if (commandLine.hasOption(optionMajor.getLongOpt())) {
                versionType = ReleaseManager.VersionType.MAJOR;
            }
            if (commandLine.hasOption(optionMinor.getLongOpt())) {
                versionType = ReleaseManager.VersionType.MINOR;
            }
            if (commandLine.hasOption(optionPatch.getLongOpt())) {
                versionType = ReleaseManager.VersionType.PATCH;
            }
            if (commandLine.hasOption(optionHotfix.getLongOpt())) {
                versionType = ReleaseManager.VersionType.HOTFIX;
            }
            // 
            if (versionType == null) {
                // minor as default
                versionType = ReleaseManager.VersionType.MINOR;
            }
            developVersion = releaseManager.getNextSnapshotVersionNumber(StringUtils.isEmpty(releaseVersion) ? currentVersion : releaseVersion, versionType);
        }
        // 
        String releasedVersion = releaseManager.release(releaseVersion, developVersion);
        // 
        LOG.info("Product version released [{}]. New development version [{}].", releasedVersion, currentVersion);
        LOG.info("Branches [{}], [{}] and tag [{}] are prepared to push into origin (use --publish command).", releaseManager.getDevelopBranch(), releaseManager.getMasterBranch(), releasedVersion);
        // publish shortcut after release
        if (commandLine.hasOption(optionReleaseAndPublish.getLongOpt())) {
            releaseManager.publish();
            LOG.info("Branches [{}], [{}] and prepared tags pushed into origin.", releaseManager.getDevelopBranch(), releaseManager.getMasterBranch());
        }
    } else if (commandLine.hasOption(optionPublish.getLongOpt())) {
        // standalone publish
        releaseManager.publish();
        LOG.info("Branches [{}], [{}] and prepared tags pushed into origin.", releaseManager.getDevelopBranch(), releaseManager.getMasterBranch());
    } else if (commandLine.hasOption(optionRevertVersion.getLongOpt())) {
        LOG.info("Current product version [{}].", releaseManager.revertVersion());
    } else if (commandLine.hasOption(optionSetVersion.getLongOpt())) {
        String developVersion = commandLine.getOptionValue(optionDevelopVersion.getLongOpt());
        // 
        LOG.info("Current product version [{}].", releaseManager.setVersion(developVersion));
    } else if (commandLine.hasOption(optionGetVersion.getLongOpt())) {
        String branch = null;
        if (commandLine.hasOption(optionDevelopBranch.getLongOpt())) {
            branch = commandLine.getOptionValue(optionDevelopBranch.getLongOpt());
        }
        String currentVersion = releaseManager.getCurrentVersion(branch);
        // 
        LOG.info("Current product version [{}].", currentVersion);
    }
    // 
    LOG.info("Complete!");
}
Also used : Arrays(java.util.Arrays) Options(org.apache.commons.cli.Options) Autowired(org.springframework.beans.factory.annotation.Autowired) HelpFormatter(org.apache.commons.cli.HelpFormatter) StringUtils(org.apache.commons.lang3.StringUtils) ProductReleaseManager(eu.bcvsolutions.idm.tool.service.impl.ProductReleaseManager) DefaultParser(org.apache.commons.cli.DefaultParser) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) CommandLine(org.apache.commons.cli.CommandLine) Console(java.io.Console) CommandLineRunner(org.springframework.boot.CommandLineRunner) Option(org.apache.commons.cli.Option) ReleaseManager(eu.bcvsolutions.idm.tool.service.api.ReleaseManager) Properties(java.util.Properties) CommandLineParser(org.apache.commons.cli.CommandLineParser) ProjectManager(eu.bcvsolutions.idm.tool.service.impl.ProjectManager) IOException(java.io.IOException) ModuleReleaseManager(eu.bcvsolutions.idm.tool.service.impl.ModuleReleaseManager) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) File(java.io.File) List(java.util.List) ParseException(org.apache.commons.cli.ParseException) OptionGroup(org.apache.commons.cli.OptionGroup) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) InputStream(java.io.InputStream) BuildException(eu.bcvsolutions.idm.tool.exception.BuildException) Options(org.apache.commons.cli.Options) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) ModuleReleaseManager(eu.bcvsolutions.idm.tool.service.impl.ModuleReleaseManager) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) ProjectManager(eu.bcvsolutions.idm.tool.service.impl.ProjectManager) ProductReleaseManager(eu.bcvsolutions.idm.tool.service.impl.ProductReleaseManager) CommandLine(org.apache.commons.cli.CommandLine) OptionGroup(org.apache.commons.cli.OptionGroup) ProductReleaseManager(eu.bcvsolutions.idm.tool.service.impl.ProductReleaseManager) ReleaseManager(eu.bcvsolutions.idm.tool.service.api.ReleaseManager) ModuleReleaseManager(eu.bcvsolutions.idm.tool.service.impl.ModuleReleaseManager) Console(java.io.Console) Option(org.apache.commons.cli.Option) CommandLineParser(org.apache.commons.cli.CommandLineParser) BuildException(eu.bcvsolutions.idm.tool.exception.BuildException) DefaultParser(org.apache.commons.cli.DefaultParser)

Example 18 with StringUtils.isNotEmpty

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

the class ReportGenerateEndSendNotificationProcessor method process.

@Override
public EventResult<RptReportDto> process(EntityEvent<RptReportDto> event) {
    RptReportDto report = event.getContent();
    UUID creatorId = report.getCreatorId();
    // 
    if (report.getResult() == null) {
        return new DefaultEventResult<>(event, this);
    }
    // 
    boolean success = report.getResult().getState() == OperationState.EXECUTED;
    List<IdmIdentityDto> recipients = new ArrayList<>(1);
    if (creatorId != null) {
        // default recipient is logged user, but can be overriden by topic configuration
        recipients.add(identityService.get(creatorId));
    }
    // 
    Builder message = new IdmMessageDto.Builder(success ? NotificationLevel.SUCCESS : NotificationLevel.WARNING).addParameter("url", configurationService.getFrontendUrl(String.format("rpt/reports?id=%s", report.getId()))).addParameter("report", report).setModel(new DefaultResultModel(success ? RptResultCode.REPORT_GENERATE_SUCCESS : RptResultCode.REPORT_GENERATE_FAILED, ImmutableMap.of("reportName", report.getName())));
    // 
    if (success) {
        // rendered reports as email attachments
        List<String> rendererNames = reportManager.getRenderers(report.getExecutorName()).stream().filter(// default json will be ignored
        renderer -> !renderer.getName().equals(DefaultJsonRenderer.RENDERER_NAME)).map(RptReportRendererDto::getName).collect(Collectors.toList());
        List<IdmAttachmentDto> attachments = attachmentManager.getAttachments(report, null).stream().filter(attachment -> StringUtils.isNotEmpty(attachment.getAttachmentType()) && rendererNames.contains(attachment.getAttachmentType())).collect(Collectors.toList());
        // 
        // load topic configuration
        String topic = null;
        IdmFormDto filter = report.getFilter();
        if (filter != null) {
            IdmFormInstanceDto formInstance = new IdmFormInstanceDto(report, formService.getDefinition(filter.getFormDefinition()), report.getFilter());
            Serializable configuredTopic = formInstance.toSinglePersistentValue(AbstractReportExecutor.PROPERTY_TOPIC_REPORT_GENERATE_SUCCESS);
            if (configuredTopic != null) {
                topic = configuredTopic.toString();
            }
        } else {
            // Backward compatibility => reports generated from code (without UI form + filter).
            topic = RptModuleDescriptor.TOPIC_REPORT_GENERATE_SUCCESS;
        }
        // topic is optional => notification will not be sent, if default value is cleared / not given.
        if (StringUtils.isEmpty(topic)) {
            LOG.debug("Report result will be not sent, topic is not configured [{}].");
        } else {
            LOG.debug("Report result will be sent to topic [{}]", topic);
            // 
            notificationManager.send(topic, message.build(), null, recipients, attachments);
        }
    } else if (creatorId != null) {
        notificationManager.send(RptModuleDescriptor.TOPIC_REPORT_GENERATE_FAILED, message.build(), identityService.get(creatorId));
    }
    // 
    return new DefaultEventResult<>(event, this);
}
Also used : IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) NotificationManager(eu.bcvsolutions.idm.core.notification.api.service.NotificationManager) IdmAttachmentDto(eu.bcvsolutions.idm.core.ecm.api.dto.IdmAttachmentDto) ReportProcessor(eu.bcvsolutions.idm.rpt.api.event.processor.ReportProcessor) ReportEventType(eu.bcvsolutions.idm.rpt.api.event.ReportEvent.ReportEventType) Autowired(org.springframework.beans.factory.annotation.Autowired) CoreEventProcessor(eu.bcvsolutions.idm.core.api.event.CoreEventProcessor) ConfigurationService(eu.bcvsolutions.idm.core.api.service.ConfigurationService) FormService(eu.bcvsolutions.idm.core.eav.api.service.FormService) ReportManager(eu.bcvsolutions.idm.rpt.api.service.ReportManager) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) RptReportRendererDto(eu.bcvsolutions.idm.rpt.api.dto.RptReportRendererDto) RptModuleDescriptor(eu.bcvsolutions.idm.rpt.RptModuleDescriptor) IdmFormDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDto) DefaultJsonRenderer(eu.bcvsolutions.idm.rpt.renderer.DefaultJsonRenderer) RptResultCode(eu.bcvsolutions.idm.rpt.api.domain.RptResultCode) DefaultEventResult(eu.bcvsolutions.idm.core.api.event.DefaultEventResult) EventResult(eu.bcvsolutions.idm.core.api.event.EventResult) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) EntityEvent(eu.bcvsolutions.idm.core.api.event.EntityEvent) Builder(eu.bcvsolutions.idm.core.notification.api.dto.IdmMessageDto.Builder) Description(org.springframework.context.annotation.Description) NotificationLevel(eu.bcvsolutions.idm.core.notification.api.domain.NotificationLevel) ImmutableMap(com.google.common.collect.ImmutableMap) AttachmentManager(eu.bcvsolutions.idm.core.ecm.api.service.AttachmentManager) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) OperationState(eu.bcvsolutions.idm.core.api.domain.OperationState) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) AbstractReportExecutor(eu.bcvsolutions.idm.rpt.api.executor.AbstractReportExecutor) Serializable(java.io.Serializable) RptReportDto(eu.bcvsolutions.idm.rpt.api.dto.RptReportDto) List(java.util.List) Component(org.springframework.stereotype.Component) IdmMessageDto(eu.bcvsolutions.idm.core.notification.api.dto.IdmMessageDto) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) IdmIdentityService(eu.bcvsolutions.idm.core.api.service.IdmIdentityService) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) Serializable(java.io.Serializable) DefaultResultModel(eu.bcvsolutions.idm.core.api.dto.DefaultResultModel) IdmMessageDto(eu.bcvsolutions.idm.core.notification.api.dto.IdmMessageDto) Builder(eu.bcvsolutions.idm.core.notification.api.dto.IdmMessageDto.Builder) ArrayList(java.util.ArrayList) IdmFormDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDto) RptReportDto(eu.bcvsolutions.idm.rpt.api.dto.RptReportDto) Builder(eu.bcvsolutions.idm.core.notification.api.dto.IdmMessageDto.Builder) DefaultEventResult(eu.bcvsolutions.idm.core.api.event.DefaultEventResult) UUID(java.util.UUID) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)

Example 19 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project okta-sdk-java by okta.

the class AbstractOktaJavaClientCodegen method fromModel.

@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
    CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
    // super add these imports, and we don't want that dependency
    codegenModel.imports.remove("ApiModel");
    if (model.getVendorExtensions().containsKey("x-baseType")) {
        String baseType = (String) model.getVendorExtensions().get("x-baseType");
        codegenModel.vendorExtensions.put("baseType", toModelName(baseType));
        codegenModel.imports.add(toModelName(baseType));
    }
    Collection<CodegenOperation> operations = (Collection<CodegenOperation>) codegenModel.vendorExtensions.get("operations");
    if (operations != null) {
        operations.forEach(op -> {
            if (op.returnType != null) {
                codegenModel.imports.add(op.returnType);
            }
            if (op.allParams != null) {
                op.allParams.stream().filter(param -> needToImport(param.dataType)).forEach(param -> codegenModel.imports.add(param.dataType));
            }
        });
    }
    // force alias == false (likely only relevant for Lists, but something changed in swagger 2.2.3 to require this)
    codegenModel.isAlias = false;
    String parent = (String) model.getVendorExtensions().get("x-okta-parent");
    if (StringUtils.isNotEmpty(parent)) {
        codegenModel.parent = toApiName(parent.substring(parent.lastIndexOf("/")));
        // figure out the resourceClass if this model has a parent
        String discriminatorRoot = getRootDiscriminator(name);
        if (discriminatorRoot != null) {
            model.getVendorExtensions().put("discriminatorRoot", discriminatorRoot);
        }
    }
    // We use '$ref' attributes with siblings, which isn't valid JSON schema (or swagger), so we need process
    // additional attributes from the raw schema
    Map<String, Object> modelDef = getRawSwaggerDefinition(name);
    codegenModel.vars.forEach(codegenProperty -> {
        Map<String, Object> rawPropertyMap = getRawSwaggerProperty(modelDef, codegenProperty.baseName);
        codegenProperty.isReadOnly = Boolean.TRUE.equals(rawPropertyMap.get("readOnly"));
    });
    return codegenModel;
}
Also used : CodegenOperation(io.swagger.codegen.CodegenOperation) SortedSet(java.util.SortedSet) LoggerFactory(org.slf4j.LoggerFactory) ModelImpl(io.swagger.models.ModelImpl) ArrayProperty(io.swagger.models.properties.ArrayProperty) StringUtils(org.apache.commons.lang3.StringUtils) Model(io.swagger.models.Model) Path(io.swagger.models.Path) Locale(java.util.Locale) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Operation(io.swagger.models.Operation) Property(io.swagger.models.properties.Property) RefModel(io.swagger.models.RefModel) Collection(java.util.Collection) Set(java.util.Set) Reader(java.io.Reader) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Response(io.swagger.models.Response) List(java.util.List) Optional(java.util.Optional) CodegenParameter(io.swagger.codegen.CodegenParameter) AbstractJavaCodegen(io.swagger.codegen.languages.AbstractJavaCodegen) Swagger(io.swagger.models.Swagger) BooleanUtils(org.apache.commons.lang3.BooleanUtils) HashMap(java.util.HashMap) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) TreeSet(java.util.TreeSet) Yaml(org.yaml.snakeyaml.Yaml) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) CodegenProperty(io.swagger.codegen.CodegenProperty) RefProperty(io.swagger.models.properties.RefProperty) Logger(org.slf4j.Logger) CodegenOperation(io.swagger.codegen.CodegenOperation) BodyParameter(io.swagger.models.parameters.BodyParameter) Iterator(java.util.Iterator) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CodegenType(io.swagger.codegen.CodegenType) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) File(java.io.File) SwaggerException(io.swagger.parser.SwaggerException) CodegenModel(io.swagger.codegen.CodegenModel) HttpMethod(io.swagger.models.HttpMethod) Collections(java.util.Collections) Collection(java.util.Collection) CodegenModel(io.swagger.codegen.CodegenModel)

Example 20 with StringUtils.isNotEmpty

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

the class StoreEndpoint method onPost.

/**
 * Handles the HTTP POST request
 * @param context the routing context
 */
private void onPost(RoutingContext context) {
    HttpServerRequest request = context.request();
    request.pause();
    String layer = getEndpointPath(context);
    String tagsStr = request.getParam("tags");
    String propertiesStr = request.getParam("props");
    String fallbackCRSString = request.getParam("fallbackCRS");
    List<String> tags = StringUtils.isNotEmpty(tagsStr) ? Splitter.on(',').trimResults().splitToList(tagsStr) : null;
    Map<String, Object> properties = new HashMap<>();
    if (StringUtils.isNotEmpty(propertiesStr)) {
        String regex = "(?<!" + Pattern.quote("\\") + ")" + Pattern.quote(":");
        String[] parts = propertiesStr.split(",");
        for (String part : parts) {
            part = part.trim();
            String[] property = part.split(regex);
            if (property.length != 2) {
                request.response().setStatusCode(400).end("Invalid property syntax: " + part);
                return;
            }
            String key = StringEscapeUtils.unescapeJava(property[0].trim());
            String value = StringEscapeUtils.unescapeJava(property[1].trim());
            properties.put(key, value);
        }
    }
    // get temporary filename
    String incoming = storagePath + "/incoming";
    String filename = new ObjectId().toString();
    String filepath = incoming + "/" + filename;
    String correlationId = UUID.randomUUID().toString();
    long startTime = System.currentTimeMillis();
    this.onReceivingFileStarted(correlationId, layer, startTime);
    // create directory for incoming files
    FileSystem fs = vertx.fileSystem();
    ObservableFuture<Void> observable = RxHelper.observableFuture();
    fs.mkdirs(incoming, observable.toHandler());
    observable.flatMap(v -> {
        // create temporary file
        ObservableFuture<AsyncFile> openObservable = RxHelper.observableFuture();
        fs.open(filepath, new OpenOptions(), openObservable.toHandler());
        return openObservable;
    }).flatMap(f -> {
        // write request body into temporary file
        ObservableFuture<Void> pumpObservable = RxHelper.observableFuture();
        Handler<AsyncResult<Void>> pumpHandler = pumpObservable.toHandler();
        Pump.pump(request, f).start();
        Handler<Throwable> errHandler = (Throwable t) -> {
            request.endHandler(null);
            f.close();
            pumpHandler.handle(Future.failedFuture(t));
        };
        f.exceptionHandler(errHandler);
        request.exceptionHandler(errHandler);
        request.endHandler(v -> {
            f.close();
            pumpHandler.handle(Future.succeededFuture());
        });
        request.resume();
        return pumpObservable;
    }).flatMap(v -> {
        String contentTypeHeader = request.getHeader("Content-Type");
        String mimeType = null;
        try {
            ContentType contentType = ContentType.parse(contentTypeHeader);
            mimeType = contentType.getMimeType();
        } catch (ParseException | IllegalArgumentException ex) {
        // mimeType already null
        }
        // detect content type of file to import
        if (mimeType == null || mimeType.trim().isEmpty() || mimeType.equals("application/octet-stream") || mimeType.equals("application/x-www-form-urlencoded")) {
            // fallback: if the client has not sent a Content-Type or if it's
            // a generic one, then try to guess it
            log.debug("Mime type '" + mimeType + "' is invalid or generic. " + "Trying to guess the right type.");
            return detectContentType(filepath).doOnNext(guessedType -> {
                log.debug("Guessed mime type '" + guessedType + "'.");
            });
        }
        return Observable.just(mimeType);
    }).subscribe(detectedContentType -> {
        long duration = System.currentTimeMillis() - startTime;
        this.onReceivingFileFinished(correlationId, duration, layer, null);
        // run importer
        JsonObject msg = new JsonObject().put("filename", filename).put("layer", layer).put("contentType", detectedContentType).put("correlationId", correlationId);
        if (tags != null) {
            msg.put("tags", new JsonArray(tags));
        }
        if (!properties.isEmpty()) {
            msg.put("properties", new JsonObject(properties));
        }
        if (fallbackCRSString != null) {
            msg.put("fallbackCRSString", fallbackCRSString);
        }
        request.response().setStatusCode(// Accepted
        202).putHeader("X-Correlation-Id", correlationId).setStatusMessage("Accepted file - importing in progress").end();
        // run importer
        vertx.eventBus().send(AddressConstants.IMPORTER_IMPORT, msg);
    }, err -> {
        long duration = System.currentTimeMillis() - startTime;
        this.onReceivingFileFinished(correlationId, duration, layer, err);
        fail(request.response(), err);
        err.printStackTrace();
        fs.delete(filepath, ar -> {
        });
    });
}
Also used : Arrays(java.util.Arrays) Router(io.vertx.ext.web.Router) RxStoreCursor(io.georocket.storage.RxStoreCursor) RoutingContext(io.vertx.ext.web.RoutingContext) StringUtils(org.apache.commons.lang3.StringUtils) ChunkMeta(io.georocket.storage.ChunkMeta) RxStore(io.georocket.storage.RxStore) StoreCursor(io.georocket.storage.StoreCursor) Single(rx.Single) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) Pump(io.vertx.core.streams.Pump) JsonObject(io.vertx.core.json.JsonObject) Logger(io.vertx.core.logging.Logger) Splitter(com.google.common.base.Splitter) OpenOptions(io.vertx.core.file.OpenOptions) ContentType(org.apache.http.entity.ContentType) UUID(java.util.UUID) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) HttpServerResponse(io.vertx.core.http.HttpServerResponse) FileSystem(io.vertx.core.file.FileSystem) RxHelper(io.vertx.rx.java.RxHelper) MultiMerger(io.georocket.output.MultiMerger) Pattern(java.util.regex.Pattern) AddressConstants(io.georocket.constants.AddressConstants) AsyncFile(io.vertx.core.file.AsyncFile) HttpServerRequest(io.vertx.core.http.HttpServerRequest) MimeTypeUtils(io.georocket.util.MimeTypeUtils) HashMap(java.util.HashMap) LoggerFactory(io.vertx.core.logging.LoggerFactory) Observable(rx.Observable) ServerAPIException(io.georocket.ServerAPIException) WriteStream(io.vertx.core.streams.WriteStream) StoreFactory(io.georocket.storage.StoreFactory) AsyncResult(io.vertx.core.AsyncResult) HttpException(io.georocket.util.HttpException) ParseException(org.apache.http.ParseException) ObservableFuture(io.vertx.rx.java.ObservableFuture) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) RxAsyncCursor(io.georocket.storage.RxAsyncCursor) File(java.io.File) JsonArray(io.vertx.core.json.JsonArray) ObjectId(org.bson.types.ObjectId) Merger(io.georocket.output.Merger) Handler(io.vertx.core.Handler) ConfigConstants(io.georocket.constants.ConfigConstants) OpenOptions(io.vertx.core.file.OpenOptions) ContentType(org.apache.http.entity.ContentType) HashMap(java.util.HashMap) ObjectId(org.bson.types.ObjectId) HttpServerRequest(io.vertx.core.http.HttpServerRequest) JsonObject(io.vertx.core.json.JsonObject) JsonArray(io.vertx.core.json.JsonArray) ObservableFuture(io.vertx.rx.java.ObservableFuture) FileSystem(io.vertx.core.file.FileSystem) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult)

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