Search in sources :

Example 26 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project dhis2-core by dhis2.

the class EventDataValuesValidationHook method validateMandatoryDataValues.

private void validateMandatoryDataValues(Event event, TrackerImportValidationContext context, ValidationErrorReporter reporter) {
    if (StringUtils.isNotEmpty(event.getProgramStage())) {
        ProgramStage programStage = context.getProgramStage(event.getProgramStage());
        final List<String> mandatoryDataElements = programStage.getProgramStageDataElements().stream().filter(ProgramStageDataElement::isCompulsory).map(de -> context.getIdentifiers().getDataElementIdScheme().getIdentifier(de.getDataElement())).collect(Collectors.toList());
        List<String> missingDataValue = validateMandatoryDataValue(programStage, event, mandatoryDataElements);
        missingDataValue.forEach(de -> reporter.addError(event, E1303, de));
    }
}
Also used : ProgramStageDataElement(org.hisp.dhis.program.ProgramStageDataElement) DataValue(org.hisp.dhis.tracker.domain.DataValue) Event(org.hisp.dhis.tracker.domain.Event) FileResource(org.hisp.dhis.fileresource.FileResource) ValidationUtils(org.hisp.dhis.system.util.ValidationUtils) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ProgramStageDataElement(org.hisp.dhis.program.ProgramStageDataElement) E1076(org.hisp.dhis.tracker.report.TrackerErrorCode.E1076) Set(java.util.Set) ValidationErrorReporter(org.hisp.dhis.tracker.report.ValidationErrorReporter) E1084(org.hisp.dhis.tracker.report.TrackerErrorCode.E1084) ValidationUtils.needsToValidateDataValues(org.hisp.dhis.tracker.validation.hooks.ValidationUtils.needsToValidateDataValues) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) ProgramStage(org.hisp.dhis.program.ProgramStage) TrackerErrorCode(org.hisp.dhis.tracker.report.TrackerErrorCode) DataElement(org.hisp.dhis.dataelement.DataElement) List(java.util.List) Component(org.springframework.stereotype.Component) E1009(org.hisp.dhis.tracker.report.TrackerErrorCode.E1009) TrackerImportValidationContext(org.hisp.dhis.tracker.validation.TrackerImportValidationContext) E1303(org.hisp.dhis.tracker.report.TrackerErrorCode.E1303) Optional(java.util.Optional) ValidationUtils.validateMandatoryDataValue(org.hisp.dhis.tracker.validation.hooks.ValidationUtils.validateMandatoryDataValue) ProgramStage(org.hisp.dhis.program.ProgramStage)

Example 27 with StringUtils.isNotEmpty

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

the class ChangePasswordPanel method initColumns.

private List<IColumn<PasswordAccountDto, String>> initColumns() {
    List<IColumn<PasswordAccountDto, String>> columns = new ArrayList<>();
    columns.add(new CheckBoxColumn<>(Model.of(""), Selectable.F_SELECTED) {

        @Override
        protected IModel<Boolean> getEnabled(IModel<PasswordAccountDto> rowModel) {
            return () -> {
                PasswordAccountDto passwordAccountDto = rowModel.getObject();
                if (!passwordAccountDto.isMidpoint() && !passwordAccountDto.isPasswordCapabilityEnabled()) {
                    passwordAccountDto.setSelected(false);
                    return false;
                }
                if (CredentialsPropagationUserControlType.ONLY_MAPPING.equals(getModelObject().getPropagation())) {
                    if (!passwordAccountDto.isMidpoint() && !passwordAccountDto.isPasswordOutbound()) {
                        passwordAccountDto.setSelected(false);
                    }
                    return false;
                }
                if (passwordAccountDto.isMidpoint() && CredentialsPropagationUserControlType.IDENTITY_MANAGER_MANDATORY.equals(getModelObject().getPropagation())) {
                    return false;
                }
                if (!passwordAccountDto.isMidpoint() && midpointAccountSelected.getObject() && passwordAccountDto.isPasswordOutbound()) {
                    passwordAccountDto.setSelected(true);
                    return false;
                }
                return true;
            };
        }

        @Override
        protected void processBehaviourOfCheckBox(IsolatedCheckBoxPanel check, IModel<PasswordAccountDto> rowModel) {
            super.processBehaviourOfCheckBox(check, rowModel);
            IModel<String> titleModel = () -> {
                PasswordAccountDto passwordAccountDto = rowModel.getObject();
                if (!getEnabled(rowModel).getObject()) {
                    String key;
                    if (!passwordAccountDto.isMidpoint() && !passwordAccountDto.isPasswordCapabilityEnabled()) {
                        key = "ChangePasswordPanel.legendMessage.no.password.capability";
                    } else {
                        key = "ChangePasswordPanel.legendMessage.policy";
                    }
                    return createStringResource(key).getString();
                }
                return "";
            };
            check.add(AttributeAppender.append("title", titleModel));
        }

        @Override
        protected void onUpdateRow(AjaxRequestTarget target, DataTable table, IModel<PasswordAccountDto> rowModel, IModel<Boolean> selected) {
            super.onUpdateRow(target, table, rowModel, selected);
            if (rowModel.getObject().isMidpoint()) {
                table.visitChildren(IsolatedCheckBoxPanel.class, (IVisitor<IsolatedCheckBoxPanel, IsolatedCheckBoxPanel>) (panel, iVisit) -> {
                    target.add(panel);
                });
            }
        }
    });
    columns.add(new AbstractColumn<PasswordAccountDto, String>(createStringResource("ChangePasswordPanel.name")) {

        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<PasswordAccountDto>> item, String componentId, final IModel<PasswordAccountDto> rowModel) {
            item.add(new Label(componentId, new IModel<>() {

                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    PasswordAccountDto dto = rowModel.getObject();
                    return dto.getDisplayName();
                }
            }));
        }
    });
    columns.add(new AbstractColumn<PasswordAccountDto, String>(createStringResource("ChangePasswordPanel.resourceName")) {

        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<PasswordAccountDto>> item, String componentId, final IModel<PasswordAccountDto> rowModel) {
            IModel<String> helpModel = () -> {
                String title = "";
                if (!rowModel.getObject().isMidpoint() && !rowModel.getObject().isPasswordCapabilityEnabled()) {
                    title = createStringResource("ChangePasswordPanel.legendMessage.no.password.capability").getString();
                }
                if (rowModel.getObject().isMaintenanceState()) {
                    title = title + (StringUtils.isEmpty(title) ? "" : " ") + createStringResource("ChangePasswordPanel.legendMessage.maintenance").getString();
                }
                return title;
            };
            item.add(new LabelWithHelpPanel(componentId, new IModel<>() {

                private static final long serialVersionUID = 1L;

                @Override
                public String getObject() {
                    PasswordAccountDto dto = rowModel.getObject();
                    return dto.getResourceName();
                }
            }) {

                @Override
                protected IModel<String> getHelpModel() {
                    return helpModel;
                }
            });
        }
    });
    IconColumn enabled = new IconColumn<PasswordAccountDto>(createStringResource("ChangePasswordPanel.enabled")) {

        @Override
        protected DisplayType getIconDisplayType(IModel<PasswordAccountDto> rowModel) {
            String cssClass = "fa fa-question text-info";
            String tooltip = "ActivationStatusType.null";
            if (rowModel != null && rowModel.getObject() != null && rowModel.getObject().isEnabled() != null) {
                if (rowModel.getObject().isEnabled()) {
                    cssClass = GuiStyleConstants.CLASS_APPROVAL_OUTCOME_ICON_APPROVED_COLORED;
                    tooltip = "ActivationStatusType.ENABLED";
                } else {
                    cssClass = GuiStyleConstants.CLASS_APPROVAL_OUTCOME_ICON_REJECTED_COLORED;
                    tooltip = "ActivationStatusType.DISABLED";
                }
            }
            return GuiDisplayTypeUtil.createDisplayType(cssClass + " fa-fw fa-lg", "", createStringResource(tooltip).getString());
        }

        @Override
        public String getCssClass() {
            return "col-lg-1";
        }
    };
    columns.add(enabled);
    columns.add(new AbstractColumn<PasswordAccountDto, String>(createStringResource("ChangePasswordPanel.passwordValidation")) {

        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<PasswordAccountDto>> cellItem, String componentId, IModel<PasswordAccountDto> rowModel) {
            IModel<List<StringLimitationResult>> limitationsModel = () -> {
                String policyOid = rowModel.getObject().getPasswordValuePolicyOid();
                if (StringUtils.isEmpty(policyOid) || !getModelObject().getPasswordPolicies().containsKey(policyOid)) {
                    return new ArrayList<>();
                }
                if (limitationsByPolicyOid.containsKey(policyOid)) {
                    return limitationsByPolicyOid.get(policyOid);
                }
                ValuePolicyType policyType = getModelObject().getPasswordPolicies().get(policyOid);
                PrismObject<? extends ObjectType> object = rowModel.getObject().getObject();
                List<StringLimitationResult> limitations = getPasswordPanel().getLimitationsForActualPassword(policyType, object);
                limitationsByPolicyOid.put(policyOid, limitations);
                return limitations;
            };
            PasswordPolicyValidationPanel validationPanel = new PasswordPolicyValidationPanel(componentId, limitationsModel);
            validationPanel.add(new VisibleEnableBehaviour() {

                @Override
                public boolean isVisible() {
                    return !limitationsModel.getObject().isEmpty();
                }
            });
            cellItem.add(validationPanel);
        }

        @Override
        public String getCssClass() {
            return "col-lg-2";
        }
    });
    columns.add(new AbstractColumn<PasswordAccountDto, String>(createStringResource("ChangePasswordPanel.propagationResult")) {

        private static final long serialVersionUID = 1L;

        @Override
        public void populateItem(Item<ICellPopulator<PasswordAccountDto>> cellItem, String componentId, IModel<PasswordAccountDto> rowModel) {
            LoadableModel<OperationResult> resultStatusModel = new LoadableModel<OperationResult>() {

                @Override
                protected OperationResult load() {
                    if (getModelObject().getProgress() == null || getModelObject().getProgress().getProgressReportActivities().isEmpty()) {
                        return null;
                    }
                    for (ProgressReportActivityDto progressActivity : getModelObject().getProgress().getProgressReportActivities()) {
                        if (rowModel.getObject().isSelected() && progressActivity.getStatus() != null && rowModel.getObject().isMidpoint() && (ProgressInformation.ActivityType.FOCUS_OPERATION.equals(progressActivity.getActivityType()) || (ProgressInformation.ActivityType.PROJECTOR.equals(progressActivity.getActivityType()) && !OperationResultStatusType.SUCCESS.equals(progressActivity.getStatus())))) {
                            return progressActivity.getOperationResult();
                        } else if (progressActivity.getStatus() != null && !rowModel.getObject().isMidpoint() && ProgressInformation.ActivityType.RESOURCE_OBJECT_OPERATION.equals(progressActivity.getActivityType()) && progressActivity.getResourceOperationResultList() != null && !progressActivity.getResourceOperationResultList().isEmpty()) {
                            String resourceOid = rowModel.getObject().getResourceOid();
                            if (StringUtils.isNotEmpty(resourceOid) && progressActivity.getResourceShadowDiscriminator() != null && resourceOid.equals(progressActivity.getResourceShadowDiscriminator().getResourceOid())) {
                                return progressActivity.getOperationResult();
                            }
                        }
                    }
                    return new OperationResult("Empty result");
                }
            };
            ColumnResultPanel resultPanel = new ColumnResultPanel(componentId, resultStatusModel) {

                @Override
                protected boolean isProjectionResult() {
                    return !rowModel.getObject().isMidpoint();
                }

                @Override
                protected DisplayType getDisplayForEmptyResult() {
                    String policyOid = rowModel.getObject().getPasswordValuePolicyOid();
                    if (StringUtils.isNotEmpty(policyOid) && ChangePasswordPanel.this.getModelObject().getPasswordPolicies().containsKey(policyOid)) {
                        if (limitationsByPolicyOid.get(policyOid) != null) {
                            var ref = new Object() {

                                boolean result = true;
                            };
                            limitationsByPolicyOid.get(policyOid).forEach((limit) -> {
                                if (ref.result && !limit.isSuccess()) {
                                    ref.result = false;
                                }
                            });
                            if (!ref.result && rowModel.getObject().isSelected()) {
                                return GuiDisplayTypeUtil.createDisplayType("fa-fw fa fa-times-circle text-muted fa-lg", "", createStringResource("ChangePasswordPanel.result.validationError").getString());
                            }
                        }
                    }
                    return null;
                }
            };
            resultPanel.setOutputMarkupId(true);
            cellItem.add(resultPanel);
        }

        @Override
        public String getCssClass() {
            return "col-lg-2";
        }
    });
    return columns;
}
Also used : PageSelfCredentials(com.evolveum.midpoint.web.page.self.PageSelfCredentials) IColumn(org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn) StringUtils(org.apache.commons.lang3.StringUtils) AuthUtil(com.evolveum.midpoint.authentication.api.util.AuthUtil) WebModelServiceUtils(com.evolveum.midpoint.gui.api.util.WebModelServiceUtils) AbstractColumn(org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn) TablePanel(com.evolveum.midpoint.web.component.data.TablePanel) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) IModel(org.apache.wicket.model.IModel) SelectorOptions(com.evolveum.midpoint.schema.SelectorOptions) Label(org.apache.wicket.markup.html.basic.Label) ProgressReportActivityDto(com.evolveum.midpoint.web.component.progress.ProgressReportActivityDto) Model(org.apache.wicket.model.Model) LabelWithHelpPanel(com.evolveum.midpoint.gui.api.component.LabelWithHelpPanel) WebComponentUtil(com.evolveum.midpoint.gui.api.util.WebComponentUtil) ResourceTypeUtil(com.evolveum.midpoint.schema.util.ResourceTypeUtil) Task(com.evolveum.midpoint.task.api.Task) AttributeModifier(org.apache.wicket.AttributeModifier) AttributeAppender(org.apache.wicket.behavior.AttributeAppender) PropertyModel(org.apache.wicket.model.PropertyModel) Item(org.apache.wicket.markup.repeater.Item) PasswordAccountDto(com.evolveum.midpoint.web.page.admin.home.dto.PasswordAccountDto) MyPasswordsDto(com.evolveum.midpoint.web.page.admin.home.dto.MyPasswordsDto) PrismReferenceValue(com.evolveum.midpoint.prism.PrismReferenceValue) LoadableModel(com.evolveum.midpoint.gui.api.model.LoadableModel) ResourceObjectDefinition(com.evolveum.midpoint.schema.processor.ResourceObjectDefinition) java.util(java.util) GuiDisplayTypeUtil(com.evolveum.midpoint.gui.api.util.GuiDisplayTypeUtil) com.evolveum.midpoint.web.component.data.column(com.evolveum.midpoint.web.component.data.column) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Trace(com.evolveum.midpoint.util.logging.Trace) ICellPopulator(org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator) CollectionUtils(org.apache.commons.collections4.CollectionUtils) GuiStyleConstants(com.evolveum.midpoint.gui.api.GuiStyleConstants) CredentialsCapabilityType(com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType) StringLimitationResult(com.evolveum.midpoint.model.api.validator.StringLimitationResult) CapabilityUtil(com.evolveum.midpoint.schema.CapabilityUtil) IVisitor(org.apache.wicket.util.visit.IVisitor) Selectable(com.evolveum.midpoint.web.component.util.Selectable) DataTable(org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable) PasswordTextField(org.apache.wicket.markup.html.form.PasswordTextField) PrismObject(com.evolveum.midpoint.prism.PrismObject) PasswordPanel(com.evolveum.midpoint.gui.api.component.password.PasswordPanel) ItemPath(com.evolveum.midpoint.prism.path.ItemPath) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) BasePanel(com.evolveum.midpoint.gui.api.component.BasePanel) WebMarkupContainer(org.apache.wicket.markup.html.WebMarkupContainer) GetOperationOptions(com.evolveum.midpoint.schema.GetOperationOptions) PrismReference(com.evolveum.midpoint.prism.PrismReference) ProgressInformation(com.evolveum.midpoint.model.api.ProgressInformation) ListDataProvider(com.evolveum.midpoint.web.component.util.ListDataProvider) VisibleEnableBehaviour(com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) DataTable(org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable) LabelWithHelpPanel(com.evolveum.midpoint.gui.api.component.LabelWithHelpPanel) Label(org.apache.wicket.markup.html.basic.Label) StringLimitationResult(com.evolveum.midpoint.model.api.validator.StringLimitationResult) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PasswordAccountDto(com.evolveum.midpoint.web.page.admin.home.dto.PasswordAccountDto) VisibleEnableBehaviour(com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour) IModel(org.apache.wicket.model.IModel) IVisitor(org.apache.wicket.util.visit.IVisitor) ICellPopulator(org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator) AjaxRequestTarget(org.apache.wicket.ajax.AjaxRequestTarget) IColumn(org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn) LoadableModel(com.evolveum.midpoint.gui.api.model.LoadableModel) ProgressReportActivityDto(com.evolveum.midpoint.web.component.progress.ProgressReportActivityDto) PrismObject(com.evolveum.midpoint.prism.PrismObject)

Example 28 with StringUtils.isNotEmpty

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

the class SamlModuleWebSecurityConfiguration method createRelyingPartyRegistration.

private static void createRelyingPartyRegistration(RelyingPartyRegistration.Builder registrationBuilder, SamlAdditionalConfiguration.Builder additionalConfigBuilder, Saml2ProviderAuthenticationModuleType providerType, String publicHttpUrlPattern, SamlModuleWebSecurityConfiguration configuration, Saml2KeyAuthenticationModuleType keysType, Saml2ServiceProviderAuthenticationModuleType serviceProviderType, ServletRequest request) {
    String linkText = providerType.getLinkText() == null ? providerType.getEntityId() : providerType.getLinkText();
    additionalConfigBuilder.nameOfUsernameAttribute(providerType.getNameOfUsernameAttribute()).linkText(linkText);
    String registrationId = StringUtils.isNotEmpty(serviceProviderType.getAliasForPath()) ? serviceProviderType.getAliasForPath() : (StringUtils.isNotEmpty(serviceProviderType.getAlias()) ? serviceProviderType.getAlias() : serviceProviderType.getEntityId());
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(StringUtils.isNotBlank(publicHttpUrlPattern) ? publicHttpUrlPattern : getBasePath((HttpServletRequest) request));
    UriComponentsBuilder ssoBuilder = builder.cloneBuilder();
    ssoBuilder.pathSegment(AuthUtil.stripSlashes(configuration.getPrefixOfModule()) + SSO_LOCATION_URL_SUFFIX);
    UriComponentsBuilder logoutBuilder = builder.cloneBuilder();
    logoutBuilder.pathSegment(AuthUtil.stripSlashes(configuration.getPrefixOfModule()) + LOGOUT_LOCATION_URL_SUFFIX);
    registrationBuilder.registrationId(registrationId).entityId(serviceProviderType.getEntityId()).assertionConsumerServiceLocation(ssoBuilder.build().toUriString()).singleLogoutServiceLocation(logoutBuilder.build().toUriString()).assertingPartyDetails(party -> {
        party.entityId(providerType.getEntityId());
        if (serviceProviderType.isSignRequests() != null) {
            party.wantAuthnRequestsSigned(Boolean.TRUE.equals(serviceProviderType.isSignRequests()));
        }
        if (providerType.getVerificationKeys() != null && !providerType.getVerificationKeys().isEmpty()) {
            party.verificationX509Credentials(c -> providerType.getVerificationKeys().forEach(verKey -> {
                byte[] certbytes = new byte[0];
                try {
                    certbytes = protector.decryptString(verKey).getBytes();
                } catch (EncryptionException e) {
                    LOGGER.error("Couldn't obtain clear string for provider verification key");
                }
                try {
                    X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certbytes));
                    c.add(new Saml2X509Credential(certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION));
                } catch (CertificateException e) {
                    LOGGER.error("Couldn't obtain certificate from " + verKey);
                }
            }));
        }
    });
    Saml2X509Credential activeCredential = null;
    ModuleSaml2SimpleKeyType simpleKeyType = keysType.getActiveSimpleKey();
    if (simpleKeyType != null) {
        activeCredential = getSaml2Credential(simpleKeyType, true);
    }
    ModuleSaml2KeyStoreKeyType storeKeyType = keysType.getActiveKeyStoreKey();
    if (storeKeyType != null) {
        activeCredential = getSaml2Credential(storeKeyType, true);
    }
    List<Saml2X509Credential> credentials = new ArrayList<>();
    if (activeCredential != null) {
        credentials.add(activeCredential);
    }
    if (keysType.getStandBySimpleKey() != null && !keysType.getStandBySimpleKey().isEmpty()) {
        for (ModuleSaml2SimpleKeyType standByKey : keysType.getStandBySimpleKey()) {
            Saml2X509Credential credential = getSaml2Credential(standByKey, false);
            if (credential != null) {
                credentials.add(credential);
            }
        }
    }
    if (keysType.getStandByKeyStoreKey() != null && !keysType.getStandByKeyStoreKey().isEmpty()) {
        for (ModuleSaml2KeyStoreKeyType standByKey : keysType.getStandByKeyStoreKey()) {
            Saml2X509Credential credential = getSaml2Credential(standByKey, false);
            if (credential != null) {
                credentials.add(credential);
            }
        }
    }
    if (!credentials.isEmpty()) {
        registrationBuilder.decryptionX509Credentials(c -> credentials.forEach(cred -> {
            if (cred.getCredentialTypes().contains(Saml2X509Credential.Saml2X509CredentialType.DECRYPTION)) {
                c.add(cred);
            }
        }));
        registrationBuilder.signingX509Credentials(c -> credentials.forEach(cred -> {
            if (cred.getCredentialTypes().contains(Saml2X509Credential.Saml2X509CredentialType.SIGNING)) {
                c.add(cred);
            }
        }));
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) CertificateFactory(java.security.cert.CertificateFactory) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InMemoryRelyingPartyRegistrationRepository(org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository) HashMap(java.util.HashMap) Trace(com.evolveum.midpoint.util.logging.Trace) StringUtils(org.apache.commons.lang3.StringUtils) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) ArrayList(java.util.ArrayList) AuthUtil(com.evolveum.midpoint.authentication.api.util.AuthUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Map(java.util.Map) PKCSException(org.bouncycastle.pkcs.PKCSException) java.security(java.security) ServletRequest(javax.servlet.ServletRequest) MidpointAssertingPartyMetadataConverter(com.evolveum.midpoint.authentication.impl.saml.MidpointAssertingPartyMetadataConverter) AuthSequenceUtil.getBasePath(com.evolveum.midpoint.authentication.impl.util.AuthSequenceUtil.getBasePath) ResourceLoader(org.springframework.core.io.ResourceLoader) Files(java.nio.file.Files) Saml2Exception(org.springframework.security.saml2.Saml2Exception) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) CertificateException(java.security.cert.CertificateException) List(java.util.List) Certificate(java.security.cert.Certificate) java.io(java.io) Paths(java.nio.file.Paths) Protector(com.evolveum.midpoint.prism.crypto.Protector) Base64Exception(org.apache.cxf.common.util.Base64Exception) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate)

Example 29 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project java-chassis by ServiceComb.

the class PojoOperationGenerator method wrapParametersToBody.

private void wrapParametersToBody(List<ParameterGenerator> bodyFields) {
    String simpleRef = MethodUtils.findSwaggerMethodName(method) + "Body";
    bodyModel = new ModelImpl();
    bodyModel.setType(ModelImpl.OBJECT);
    for (ParameterGenerator parameterGenerator : bodyFields) {
        // to collect all information by swagger mechanism
        // must have a parameter type
        // but all these parameters will be wrap to be one body parameter, their parameter type must be null
        // so we first set to be BODY, after collected, set back to be null
        parameterGenerator.setHttpParameterType(HttpParameterType.BODY);
        scanMethodParameter(parameterGenerator);
        Property property = ModelConverters.getInstance().readAsProperty(parameterGenerator.getGenericType());
        property.setDescription(parameterGenerator.getGeneratedParameter().getDescription());
        bodyModel.addProperty(parameterGenerator.getParameterName(), property);
        parameterGenerator.setHttpParameterType(null);
    }
    swagger.addDefinition(simpleRef, bodyModel);
    SwaggerGeneratorFeature feature = swaggerGenerator.getSwaggerGeneratorFeature();
    // if not care for this, then can just delete all logic about EXT_JAVA_CLASS/EXT_JAVA_INTF
    if (feature.isExtJavaClassInVendor() && bodyFields.size() > 1 && StringUtils.isNotEmpty(feature.getPackageName())) {
        bodyModel.getVendorExtensions().put(SwaggerConst.EXT_JAVA_CLASS, feature.getPackageName() + "." + simpleRef);
    }
    RefModel refModel = new RefModel();
    refModel.setReference("#/definitions/" + simpleRef);
    bodyParameter = new BodyParameter();
    bodyParameter.name(simpleRef);
    bodyParameter.setSchema(refModel);
    bodyParameter.setName(parameterGenerators.size() == 1 ? parameterGenerators.get(0).getParameterName() : simpleRef);
    List<ParameterGenerator> newParameterGenerators = new ArrayList<>();
    newParameterGenerators.add(new ParameterGenerator(bodyParameter.getName(), Collections.emptyList(), null, HttpParameterType.BODY, bodyParameter));
    parameterGenerators.stream().filter(p -> p.getHttpParameterType() != null).forEach(p -> newParameterGenerators.add(p));
    parameterGenerators = newParameterGenerators;
}
Also used : ModelConverters(io.swagger.converter.ModelConverters) Swagger(io.swagger.models.Swagger) HttpParameterType(org.apache.servicecomb.swagger.generator.core.model.HttpParameterType) SwaggerUtils(org.apache.servicecomb.swagger.SwaggerUtils) ModelImpl(io.swagger.models.ModelImpl) StringUtils(org.apache.commons.lang3.StringUtils) HttpMethod(javax.ws.rs.HttpMethod) ArrayList(java.util.ArrayList) Map(java.util.Map) SwaggerGeneratorFeature(org.apache.servicecomb.swagger.generator.SwaggerGeneratorFeature) AbstractOperationGenerator(org.apache.servicecomb.swagger.generator.core.AbstractOperationGenerator) JavaType(com.fasterxml.jackson.databind.JavaType) Method(java.lang.reflect.Method) Property(io.swagger.models.properties.Property) RefModel(io.swagger.models.RefModel) BodyParameter(io.swagger.models.parameters.BodyParameter) AbstractSwaggerGenerator(org.apache.servicecomb.swagger.generator.core.AbstractSwaggerGenerator) Parameter(io.swagger.models.parameters.Parameter) MethodUtils(org.apache.servicecomb.swagger.generator.core.utils.MethodUtils) Collectors(java.util.stream.Collectors) List(java.util.List) ParameterGenerator(org.apache.servicecomb.swagger.generator.ParameterGenerator) SwaggerConst(org.apache.servicecomb.swagger.generator.SwaggerConst) Annotation(java.lang.annotation.Annotation) Collections(java.util.Collections) SwaggerGeneratorFeature(org.apache.servicecomb.swagger.generator.SwaggerGeneratorFeature) RefModel(io.swagger.models.RefModel) ArrayList(java.util.ArrayList) ModelImpl(io.swagger.models.ModelImpl) ParameterGenerator(org.apache.servicecomb.swagger.generator.ParameterGenerator) BodyParameter(io.swagger.models.parameters.BodyParameter) Property(io.swagger.models.properties.Property)

Example 30 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project gravitee-management-rest-api by gravitee-io.

the class ConfigServiceImpl method loadConfigByReference.

private void loadConfigByReference(Object[] objects, AbstractCommonSettingsEntity configEntity, String referenceId, ParameterReferenceType referenceType) {
    // get values from DB
    final List<Key> parameterKeys = new ArrayList<>();
    for (Object o : objects) {
        for (Field f : o.getClass().getDeclaredFields()) {
            ParameterKey parameterKey = f.getAnnotation(ParameterKey.class);
            if (parameterKey != null) {
                parameterKeys.add(parameterKey.value());
            }
        }
    }
    Map<String, List<String>> parameterMap = parameterService.findAll(parameterKeys, value -> value == null ? null : value.trim(), referenceId, referenceType);
    // set values
    for (Object o : objects) {
        for (Field f : o.getClass().getDeclaredFields()) {
            ParameterKey parameterKey = f.getAnnotation(ParameterKey.class);
            if (parameterKey != null) {
                boolean accessible = f.isAccessible();
                f.setAccessible(true);
                try {
                    List<String> values = parameterMap.get(parameterKey.value().key());
                    if (environment.containsProperty(parameterKey.value().key())) {
                        configEntity.getMetadata().add(PortalSettingsEntity.METADATA_READONLY, parameterKey.value().key());
                    }
                    final String defaultValue = parameterKey.value().defaultValue();
                    if (Enabled.class.isAssignableFrom(f.getType())) {
                        f.set(o, Boolean.parseBoolean(getFirstValueOrDefault(values, defaultValue)) ? new Enabled(true) : new Enabled(false));
                    } else if (Boolean.class.isAssignableFrom(f.getType())) {
                        f.set(o, Boolean.valueOf(getFirstValueOrDefault(values, defaultValue)));
                    } else if (Integer.class.isAssignableFrom(f.getType())) {
                        f.set(o, Integer.valueOf(getFirstValueOrDefault(values, defaultValue)));
                    } else if (Long.class.isAssignableFrom(f.getType())) {
                        f.set(o, Long.valueOf(getFirstValueOrDefault(values, defaultValue)));
                    } else if (List.class.isAssignableFrom(f.getType())) {
                        if (values == null || values.isEmpty()) {
                            if (StringUtils.isNotEmpty(defaultValue)) {
                                f.set(o, Arrays.asList(defaultValue.split(SEPARATOR)));
                            } else {
                                f.set(o, emptyList());
                            }
                        } else {
                            f.set(o, values);
                        }
                    } else if (Map.class.isAssignableFrom(f.getType())) {
                        if (values == null || values.isEmpty()) {
                            if (defaultValue == null) {
                                f.set(o, emptyMap());
                            } else {
                                f.set(o, singletonMap(defaultValue.split(KV_SEPARATOR)[0], defaultValue.split(KV_SEPARATOR)[1]));
                            }
                        } else {
                            f.set(o, values.stream().collect(toMap(v -> v.split(KV_SEPARATOR)[0], v -> {
                                final String[] split = v.split(KV_SEPARATOR);
                                if (split.length < 2) {
                                    return "";
                                }
                                return split[1];
                            })));
                        }
                    } else {
                        // If the parameter contains a sensitive info, we return dummy value
                        if (!parameterKey.sensitive()) {
                            f.set(o, getFirstValueOrDefault(values, defaultValue));
                        } else {
                            f.set(o, SENSITIVE_VALUE);
                        }
                    }
                } catch (IllegalAccessException e) {
                    LOGGER.error("Unable to set parameter {}. Use the default value", parameterKey.value().key(), e);
                }
                f.setAccessible(accessible);
            }
        }
    }
}
Also used : ConfigService(io.gravitee.rest.api.service.ConfigService) Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) SEPARATOR(io.gravitee.rest.api.service.impl.ParameterServiceImpl.SEPARATOR) StringUtils(org.apache.commons.lang3.StringUtils) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) ArrayList(java.util.ArrayList) NewsletterService(io.gravitee.rest.api.service.NewsletterService) Collectors.toMap(java.util.stream.Collectors.toMap) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) Map(java.util.Map) ParameterService(io.gravitee.rest.api.service.ParameterService) Logger(org.slf4j.Logger) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) io.gravitee.rest.api.model.settings(io.gravitee.rest.api.model.settings) Field(java.lang.reflect.Field) Key(io.gravitee.rest.api.model.parameters.Key) List(java.util.List) Component(org.springframework.stereotype.Component) ParameterKey(io.gravitee.rest.api.model.annotations.ParameterKey) KV_SEPARATOR(io.gravitee.rest.api.service.impl.ParameterServiceImpl.KV_SEPARATOR) Collections(java.util.Collections) ReCaptchaService(io.gravitee.rest.api.service.ReCaptchaService) ArrayList(java.util.ArrayList) ParameterKey(io.gravitee.rest.api.model.annotations.ParameterKey) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) List(java.util.List) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) Key(io.gravitee.rest.api.model.parameters.Key) ParameterKey(io.gravitee.rest.api.model.annotations.ParameterKey)

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