Example usage for org.apache.commons.lang BooleanUtils isTrue

List of usage examples for org.apache.commons.lang BooleanUtils isTrue

Introduction

In this page you can find the example usage for org.apache.commons.lang BooleanUtils isTrue.

Prototype

public static boolean isTrue(Boolean bool) 

Source Link

Document

Checks if a Boolean value is true, handling null by returning false.

 BooleanUtils.isTrue(Boolean.TRUE)  = true BooleanUtils.isTrue(Boolean.FALSE) = false BooleanUtils.isTrue(null)          = false 

Usage

From source file:jp.primecloud.auto.service.impl.ComponentServiceImpl.java

/**
 * {@inheritDoc}// w  w w.j a va  2  s .c  om
 */
@Override
public List<ComponentTypeDto> getComponentTypes(Long farmNo) {
    List<ComponentTypeDto> dtos = new ArrayList<ComponentTypeDto>();

    List<ComponentType> componentTypes = componentTypeDao.readAll();

    // ????
    List<Component> components = componentDao.readByFarmNo(farmNo);

    // ??
    List<Instance> instances = new ArrayList<Instance>();
    List<Instance> allInstances = instanceDao.readByFarmNo(farmNo);
    for (Instance instance : allInstances) {
        // ?
        if (BooleanUtils.isTrue(instance.getLoadBalancer())) {
            continue;
        }

        instances.add(instance);
    }

    for (ComponentType componentType : componentTypes) {
        // ???????
        if (ComponentConstants.LAYER_NAME_LB.equals(componentType.getLayer())) {
            continue;
        }

        // ?
        List<Long> availableInstanceNos = new ArrayList<Long>();

        // ??????
        for (Instance instance : instances) {
            Image image = imageDao.read(instance.getImageNo());
            String[] componentTypeNos = StringUtils.split(image.getComponentTypeNos(), ",");
            boolean available = false;
            for (String componentTypeNo : componentTypeNos) {
                if (componentType.getComponentTypeNo().equals(Long.parseLong(componentTypeNo.trim()))) {
                    available = true;
                    break;
                }
            }
            if (available) {
                availableInstanceNos.add(instance.getInstanceNo());
            }
        }

        // ??????????????????????????
        for (Component component : components) {
            ComponentType type = componentTypeDao.read(component.getComponentTypeNo());
            if (StringUtils.equals(componentType.getLayer(), type.getLayer())) {
                List<ComponentInstance> componentInstances = componentInstanceDao
                        .readByComponentNo(component.getComponentNo());
                for (ComponentInstance componentInstance : componentInstances) {
                    ComponentInstanceStatus status = ComponentInstanceStatus
                            .fromStatus(componentInstance.getStatus());
                    if (BooleanUtils.isTrue(componentInstance.getAssociate())
                            || status != ComponentInstanceStatus.STOPPED) {
                        availableInstanceNos.remove(componentInstance.getInstanceNo());
                    }
                }
            }
        }

        // DTO??
        ComponentTypeDto dto = new ComponentTypeDto();
        dto.setComponentType(componentType);
        dto.setInstanceNos(availableInstanceNos);

        dtos.add(dto);
    }

    // 
    Collections.sort(dtos, Comparators.COMPARATOR_COMPONENT_TYPE_DTO);

    return dtos;
}

From source file:com.haulmont.cuba.gui.WindowManager.java

protected OpenType overrideOpenTypeParams(OpenType mutableOpenType, DialogOptions dialogOptions) {
    if (BooleanUtils.isTrue(dialogOptions.getForceDialog())) {
        mutableOpenType.setOpenMode(OpenMode.DIALOG);
    }//from   w ww  .  ja  v  a  2 s .c o  m

    if (dialogOptions.getHeight() != null) {
        mutableOpenType.setHeight(dialogOptions.getHeight());
    }

    if (dialogOptions.getHeightUnit() != null) {
        mutableOpenType.setHeightUnit(dialogOptions.getHeightUnit());
    }

    if (dialogOptions.getWidth() != null) {
        mutableOpenType.setWidth(dialogOptions.getWidth());
    }

    if (dialogOptions.getWidthUnit() != null) {
        mutableOpenType.setWidthUnit(dialogOptions.getWidthUnit());
    }

    if (dialogOptions.getResizable() != null) {
        mutableOpenType.setResizable(dialogOptions.getResizable());
    }

    if (dialogOptions.getCloseable() != null) {
        mutableOpenType.setCloseable(dialogOptions.getCloseable());
    }

    if (dialogOptions.getModal() != null) {
        mutableOpenType.setModal(dialogOptions.getModal());
    }

    if (dialogOptions.getCloseOnClickOutside() != null) {
        mutableOpenType.setCloseOnClickOutside(dialogOptions.getCloseOnClickOutside());
    }

    if (dialogOptions.getMaximized() != null) {
        mutableOpenType.setMaximized(dialogOptions.getMaximized());
    }

    if (dialogOptions.getPositionX() != null) {
        mutableOpenType.setPositionX(dialogOptions.getPositionX());
    }

    if (dialogOptions.getPositionY() != null) {
        mutableOpenType.setPositionY(dialogOptions.getPositionY());
    }

    return mutableOpenType;
}

From source file:com.square.core.service.implementations.PersonneServiceImplementation.java

@Override
public CoordonneesDto creerOuMettreAJourCoordonnees(CoordonneesDto coordonnees, Boolean impacterFamille,
        Boolean forcerDesactivationEservices) {
    final RapportDto rapportCoordonnees = new RapportDto();

    if (coordonnees == null) {
        throw new BusinessException(
                messageSourceUtil.get(PersonnePhysiqueKeyUtil.MESSAGE_ERREUR_PERSONNE_DTO_NULL));
    }//from  w w w . ja va  2 s .  c o  m

    if (coordonnees.getIdPersonne() == null) {
        throw new BusinessException(
                messageSourceUtil.get(PersonnePhysiqueKeyUtil.MESSAGE_ERREUR_PERSONNE_NULL));
    }

    final Long idNatureMobilePrive = squareMappingService.getIdNatureMobilePrive();
    final Long idNatureMobileTravail = squareMappingService.getIdNatureMobileTravail();

    // Controles gnriques (Au moins 1 moyen de communication)
    boolean unEmailTrouve = false;
    boolean unTelephoneTrouve = false;
    if (coordonnees.getEmails() != null) {
        for (EmailDto email : coordonnees.getEmails()) {
            if (email.getAdresse() != null && !"".equals(email.getAdresse().trim())) {
                unEmailTrouve = true;
                break;
            }
        }
    }
    if (coordonnees.getTelephones() != null) {
        for (TelephoneDto telephone : coordonnees.getTelephones()) {
            if (telephone != null && telephone.getNumero() != null
                    && !"".equals(telephone.getNumero().trim())) {
                unTelephoneTrouve = true;
                break;
            }
        }
    }

    // Rcupration de la personne en base.
    final Personne personnePrincipale = personneDao.rechercherPersonneParId(coordonnees.getIdPersonne());
    if (personnePrincipale == null) {
        throw new BusinessException(
                messageSourceUtil.get(PersonnePhysiqueKeyUtil.MESSAGE_ERREUR_PERSONNE_INEXISTANTE));
    }
    final boolean isAdherent = personnePrincipale instanceof PersonnePhysique
            && ((PersonnePhysique) personnePrincipale).getNature().getId()
                    .equals(squareMappingService.getIdNaturePersonneAdherent());

    // Rcupration de la nature de la personne si personne physique
    Long idNaturePersonnePrincipale = null;
    final PersonnePhysique personnePrincipalePhysique = personnePhysiqueDao
            .rechercherPersonneParId(personnePrincipale.getId());
    if (personnePrincipalePhysique != null && personnePrincipalePhysique.getNature() != null) {
        idNaturePersonnePrincipale = personnePrincipalePhysique.getNature().getId();
    }
    final Long idNaturePersonneVivier = squareMappingService.getIdNaturePersonneVivier();
    final Long idNaturePersonneBeneficiaireVivier = squareMappingService
            .getIdNaturePersonneBeneficiaireVivier();

    // validationExpressionUtil
    // .verifierSiVrai(rapport, null, PersonnePhysiqueKeyUtil.MESSAGE_ERREUR_COORDONNEE_OBLIGATOIRE, testUnMoyenDeCommMin,
    // CoordonneesDto.class.getSimpleName() + ".telephones")
    // .verifierSiVrai(rapport, null, PersonnePhysiqueKeyUtil.MESSAGE_ERREUR_COORDONNEE_OBLIGATOIRE, testUnMoyenDeCommMin,
    // CoordonneesDto.class.getSimpleName() + ".emails");
    // FIXME Pour le moment, on leve une exception car non pris en charge pour l'affichage de l'interface
    if (!unEmailTrouve && !unTelephoneTrouve && !idNaturePersonneVivier.equals(idNaturePersonnePrincipale)
            && !idNaturePersonneBeneficiaireVivier.equals(idNaturePersonnePrincipale)) {
        throw new BusinessException(
                messageSourceUtil.get(PersonnePhysiqueKeyUtil.MESSAGE_ERREUR_COORDONNEE_OBLIGATOIRE));
    }

    final Set<Personne> personnes = new LinkedHashSet<Personne>();
    // On recherche les membres de la famille de la personne
    final Set<Personne> famille = getFamille(personnePrincipale);
    // Si le flag qui indique si l'on doit ajouter la nouvelle adresse aux bnficiaires n'est pas spcifi
    // Si la personne a une famille, on lve une exception car le flag impacterBeneficiaires doit tre renseign
    // pour dterminer si il faut ajouter l'adresse aux membres de la famille de la personne
    if (impacterFamille == null && famille.size() > 0) {
        throw new ConfirmationImpacterFamilleException(
                messageSourceUtil.get(PersonnePhysiqueKeyUtil.CONFIRMATION_IMPACTER_FAMILLE,
                        new String[] { String.valueOf(famille.size()) }));
    }
    personnes.add(personnePrincipale);
    if (BooleanUtils.isTrue(impacterFamille)) {
        // On ajoute les membres de la famille  la liste des personnes concernes par la cration de nouvelles coordonnes
        personnes.addAll(famille);
    }
    final Calendar maintenant = Calendar.getInstance();

    boolean desactiverEserviceTelephone = false;
    boolean desactiverEserviceEmail = false;

    // Traitement des tlphones
    int nbTelephonesMobile = 0;
    if (coordonnees.getTelephones() != null && !coordonnees.getTelephones().isEmpty()) {
        for (int i = 0; i < coordonnees.getTelephones().size(); i++) {
            final TelephoneDto telephoneDto = coordonnees.getTelephones().get(i);
            final boolean numeroRenseigne = StringUtils.isNotBlank(telephoneDto.getNumero());
            if (telephoneDto.getNature() != null
                    && (telephoneDto.getNature().getIdentifiant().equals(idNatureMobilePrive)
                            || telephoneDto.getNature().getIdentifiant().equals(idNatureMobileTravail))
                    && numeroRenseigne) {
                nbTelephonesMobile++;
            }
            boolean isTelephoneModifie = false;
            if (telephoneDto.getId() != null) {
                // On rcupre le tlphone  mettre  jour  partir de la base de donnes
                final Telephone telephoneAMaj = telephoneDao.rechercherTelephoneParId(telephoneDto.getId());
                // Si on recoit un id ici, mais que le numro n'est pas renseign, il faut supprimer le tlphone correspondant
                // Note : on ne supprime pas tous les tlphones car d'autres peuvent exister mais ne pas tre affichs dans Square
                if (!numeroRenseigne) {
                    // Si il faut impacter toute la famille, ou que le tlphone est li  la personne principale uniquement
                    if (BooleanUtils.isTrue(impacterFamille) || telephoneAMaj.getPersonnes().size() == 1) {
                        // On supprime le tlphone
                        supprimerTelephone(telephoneAMaj, maintenant);
                    } else {
                        // On enlve le tlphone de la liste des tlphones de la personne principale
                        personnePrincipale.removeTelephone(telephoneAMaj);
                        // on verifie si la personne est le porteur
                        if (telephoneAMaj.getPorteurUid() != null
                                && telephoneAMaj.getPorteurUid().equals(personnePrincipale.getId())) {
                            // on supprime l'identifiant externe et le porteur du telephone restant sur la famille
                            telephoneAMaj.setIdentifiantExterieur(null);
                            telephoneAMaj.setPorteurUid(null);
                        }
                    }
                    continue;
                } else {
                    // Sinon on dtermine si le tlphone a t modifi
                    isTelephoneModifie = isTelephoneModifie(telephoneAMaj, telephoneDto);
                    // Si le tlphone existe et a t modifi, et qu'il ne faut pas impacter la famille
                    if (BooleanUtils.isFalse(impacterFamille) && isTelephoneModifie
                            && telephoneAMaj.getPersonnes().size() > 1) {
                        // on supprime le telephone de la personne
                        personnePrincipale.removeTelephone(telephoneAMaj);
                        // on supprime l'identifiant pour crer un nouveau telephone
                        telephoneDto.setId(null);
                        // on verifie si la personne est le porteur
                        if (telephoneAMaj.getPorteurUid() != null
                                && telephoneAMaj.getPorteurUid().equals(personnePrincipale.getId())) {
                            // on supprime l'identifiant externe et le porteur du telephone restant sur la famille (pas de synchro aia)
                            telephoneAMaj.setIdentifiantExterieur(null);
                            telephoneAMaj.setPorteurUid(null);
                        } else {
                            // On supprime l'identifiant externe afin de ne pas synchroniser avec aia
                            telephoneDto.setIdext(null);
                        }
                    }
                }
            }
            if (numeroRenseigne) {
                final RapportDto rapportTelephone = new RapportDto();
                controlerTelephone(rapportTelephone, telephoneDto, i);
                if (rapportTelephone.getRapports() != null && !rapportTelephone.getRapports().isEmpty()) {
                    for (String key : rapportTelephone.getRapports().keySet()) {
                        final SousRapportDto sousRapport = rapportTelephone.getRapports().get(key);
                        rapportCoordonnees.ajoutRapport(sousRapport.getAttribut(), sousRapport.getMessage(),
                                sousRapport.getErreur());
                    }
                }
                if (!rapportTelephone.getEnErreur()) {
                    final Telephone telephone = creerOuMettreAJourTelephone(personnes, telephoneDto,
                            impacterFamille);
                    if (telephone.getId() == null) {
                        // On rattache le tlphone  la personne principale
                        personnePrincipale.addTelephone(telephone);
                        if (BooleanUtils.isTrue(impacterFamille)) {
                            // On rattache aussi le tlphone aux membres de sa famille
                            for (Personne personne : famille) {
                                // bug 8832 : on impacte que ceux qui n'ont pas deja de telephones
                                if (personne.getTelephones().size() == 0) {
                                    personne.addTelephone(telephone);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // on desactive l'envoi par telephone
    if (nbTelephonesMobile == 0 && isAdherent) {
        // on verifie si la personne possede l'eservice
        final List<Long> optionsSouscrites = adherentService
                .getListeIdsTypesOptionsSouscrites(personnePrincipale.getId());
        boolean possedeEserviceTelephone = false;
        for (Long idTypeOption : optionsSouscrites) {
            if (idTypeOption.equals(adherentMappingService.getIdTypeOptionEnvoiSms())) {
                possedeEserviceTelephone = true;
                break;
            }
        }
        desactiverEserviceTelephone = possedeEserviceTelephone;
    }

    // Traitement des emails
    if (coordonnees.getEmails() != null && !coordonnees.getEmails().isEmpty()) {
        for (int i = 0; i < coordonnees.getEmails().size(); i++) {
            final EmailDto emailDto = coordonnees.getEmails().get(i);
            final boolean adresseEmailRenseignee = StringUtils.isNotBlank(emailDto.getAdresse());
            boolean isEmailModifie = false;

            // FIXME : La constante nature de l'email devrait elle etre fournie par le client ?
            emailDto.setNatureEmail(
                    new IdentifiantLibelleDto(squareMappingService.getIdNatureEmailPersonnel()));

            if (emailDto.getIdentifiant() != null) {
                // On rcupre l'email  mettre  jour  partir de la base de donnes
                final Email emailAMaj = emailDao.rechercherEmailParId(emailDto.getIdentifiant());
                // Si on recoit un id ici, mais que les infos ne sont pas renseignes, il faut supprimer le tlphone correspondant
                // Note : on ne supprime pas tous les tlphones car d'autres peuvent exister mais ne pas tre affichs dans Square
                if (!adresseEmailRenseignee) {
                    // Si il faut impacter toute la famille, ou que l'email est li  la personne principale uniquement
                    if (BooleanUtils.isTrue(impacterFamille) || emailAMaj.getPersonnes().size() == 1) {
                        // On supprime l'email
                        supprimerEmail(emailAMaj, maintenant);
                    } else {
                        // On enlve le tlphone de la liste des tlphones de la personne principale
                        personnePrincipale.removeEmail(emailAMaj);
                        // on verifie si la personne est le porteur
                        if (emailAMaj.getPorteurUid() != null
                                && emailAMaj.getPorteurUid().equals(personnePrincipale.getId())) {
                            // on supprime l'identifiant externe et le porteur de l'email restant sur la famille
                            emailAMaj.setIdentifiantExterieur(null);
                            emailAMaj.setPorteurUid(null);
                        }
                    }
                    if (isAdherent) {
                        // on verifie si la personne possede l'eservice
                        final List<Long> optionsSouscrites = adherentService
                                .getListeIdsTypesOptionsSouscrites(personnePrincipale.getId());
                        boolean possedeEserviceEmail = false;
                        for (Long idTypeOption : optionsSouscrites) {
                            if (idTypeOption
                                    .equals(adherentMappingService.getIdTypeOptionEnvoiMutuellementEmail())
                                    || idTypeOption.equals(adherentMappingService
                                            .getIdTypeOptionEnvoiRelevesPrestationEmail())) {
                                possedeEserviceEmail = true;
                                break;
                            }
                        }
                        desactiverEserviceEmail = possedeEserviceEmail;
                    }
                    continue;
                } else {
                    // Sinon on dtermine si l'email a t modifi
                    isEmailModifie = isEmailModifie(emailAMaj, emailDto);
                    // Si le tlphone existe et a t modifi, et qu'il ne faut pas impacter la famille
                    if (BooleanUtils.isFalse(impacterFamille) && isEmailModifie
                            && emailAMaj.getPersonnes().size() > 1) {
                        // on supprime l'email de la personne
                        personnePrincipale.removeEmail(emailAMaj);
                        // on supprime l'identifiant pour crer un nouvel email
                        emailDto.setIdentifiant(null);
                        // on verifie si la personne est le porteur
                        if (emailAMaj.getPorteurUid() != null
                                && emailAMaj.getPorteurUid().equals(personnePrincipale.getId())) {
                            // on supprime l'identifiant externe et le porteur de l'email restant sur la famille (pas de synchro aia)
                            emailAMaj.setIdentifiantExterieur(null);
                            emailAMaj.setPorteurUid(null);
                        } else {
                            // On supprime l'identifiant externe afin de ne pas synchroniser avec aia
                            emailDto.setIdext(null);
                        }
                    }
                }
            }
            if (adresseEmailRenseignee) {
                final RapportDto rapportEmail = new RapportDto();
                controlerEmail(rapportEmail, emailDto, i);
                if (rapportEmail.getRapports() != null && !rapportEmail.getRapports().isEmpty()) {
                    for (String key : rapportEmail.getRapports().keySet()) {
                        final SousRapportDto sousRapport = rapportEmail.getRapports().get(key);
                        rapportCoordonnees.ajoutRapport(sousRapport.getAttribut(), sousRapport.getMessage(),
                                sousRapport.getErreur());
                    }
                }
                if (!rapportEmail.getEnErreur()) {
                    final Email email = creerOuMettreAJourEmail(personnes, emailDto, impacterFamille);
                    // Si c'est un nouvel email
                    if (email.getId() == null) {
                        // On rattache le nouvel email  la personne principale
                        personnePrincipale.addEMail(email);
                        if (BooleanUtils.isTrue(impacterFamille)) {
                            // On rattache aussi le nouvel email aux membres de sa famille
                            for (Personne personne : famille) {
                                // bug 8832 : on impacte que ceux qui n'ont pas deja d'emails
                                if (personne.getEmails().size() == 0) {
                                    personne.addEMail(email);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // on desactive les eservices suivant les besoins
    if (!BooleanUtils.isTrue(forcerDesactivationEservices)) {
        if (desactiverEserviceTelephone && desactiverEserviceEmail) {
            throw new ConfirmationDesactivationEserviceException(messageSourceUtil
                    .get(PersonneKeyUtil.MESSAGE_CONFIRMATION_DESACTIVATION_ESERVICE_TELEPHONE_ET_EMAIL));
        } else if (desactiverEserviceTelephone) {
            throw new ConfirmationDesactivationEserviceException(messageSourceUtil
                    .get(PersonneKeyUtil.MESSAGE_CONFIRMATION_DESACTIVATION_ESERVICE_TELEPHONE));
        } else if (desactiverEserviceEmail) {
            throw new ConfirmationDesactivationEserviceException(
                    messageSourceUtil.get(PersonneKeyUtil.MESSAGE_CONFIRMATION_DESACTIVATION_ESERVICE_EMAIL));
        }
    } else {
        if (desactiverEserviceTelephone) {
            adherentService.desactiverOptionsEnvoiParTelephone(personnePrincipale.getId());
        }
        if (desactiverEserviceEmail) {
            adherentService.desactiverOptionsEnvoiParEmail(personnePrincipale.getId());
        }
    }

    // Recherche de l'adresse principale en cours
    final AdresseCriteresRechercheDto criteresRechercheAdressePrincipale = new AdresseCriteresRechercheDto();
    criteresRechercheAdressePrincipale.setIdPersonne(personnePrincipale.getId());
    criteresRechercheAdressePrincipale.setIdNature(squareMappingService.getIdNatureAdressePrincipale());
    criteresRechercheAdressePrincipale.setActive(true);
    final List<Adresse> listAddressesPrin = adresseDao
            .rechercherAdresseParCritere(criteresRechercheAdressePrincipale);
    Adresse adressePrincipaleEnCours = new Adresse();
    boolean plusQueAdressePrincipale = false;
    boolean choixPasserEnSecondaire = false;
    if (listAddressesPrin != null && listAddressesPrin.size() > 0) {
        adressePrincipaleEnCours = listAddressesPrin.get(0);
    }
    Calendar dateFinAdressePrincipale = null;

    // Traitement des adresses
    if (coordonnees.getAdresses() != null && !coordonnees.getAdresses().isEmpty()) {
        final RapportDto rapportAdresses = new RapportDto();
        for (int i = 0; i < coordonnees.getAdresses().size(); i++) {
            final AdresseDto adresseDto = coordonnees.getAdresses().get(i);

            if (adresseDto.getNature() != null
                    && adresseDto.getNature().getIdentifiant()
                            .equals(squareMappingService.getIdNatureAdressePrincipale())
                    && adressePrincipaleEnCours.getId() != null
                    && !adressePrincipaleEnCours.getId().equals(adresseDto.getIdentifiant())
                    && (adresseDto.getDateFin() == null
                            || Calendar.getInstance().before(adresseDto.getDateFin()))) {

                dateFinAdressePrincipale = adresseDto.getDateDebut();
                if (!choixPasserEnSecondaire) {
                    choixPasserEnSecondaire = adresseDto.getChoixPasserEnSecondaire() == null ? false
                            : adresseDto.getChoixPasserEnSecondaire().booleanValue();
                }
                plusQueAdressePrincipale = true;
            }

            final RapportDto rapportAdresse = new RapportDto();
            controlerAdresse(rapportAdresse, adresseDto, i);
            if (rapportAdresse.getRapports() != null && !rapportAdresse.getRapports().isEmpty()) {
                for (String key : rapportAdresse.getRapports().keySet()) {
                    final SousRapportDto sousRapport = rapportAdresse.getRapports().get(key);
                    rapportCoordonnees.ajoutRapport(sousRapport.getAttribut(), sousRapport.getMessage(),
                            sousRapport.getErreur());
                }
            }
            if (!rapportAdresse.getEnErreur()) {
                if (adresseDto.getIdentifiant() != null) {
                    final Adresse adresseAMaj = adresseDao.rechercherAdresseParId(adresseDto.getIdentifiant());
                    final boolean isAdresseModifiee = isAdresseModifiee(adresseAMaj, adresseDto);
                    // Si l'adresse existe et a t modifie, et qu'il ne faut pas impacter la famille
                    if (BooleanUtils.isFalse(impacterFamille) && isAdresseModifiee
                            && adresseAMaj.getPersonnes().size() > 1) {
                        // on supprime l'adresse de la personne
                        personnePrincipale.removeAdresse(adresseAMaj);
                        // On supprime l'identifiant de l'adresse afin de crer une nouvelle adresse
                        adresseDto.setIdentifiant(null);
                        // on verifie si la personne est le porteur
                        if (adresseAMaj.getPorteurUid() != null
                                && adresseAMaj.getPorteurUid().equals(personnePrincipale.getId())) {
                            // on supprime l'identifiant externe et le porteur de l'adresse restante sur la famille (pas de synchro aia)
                            adresseAMaj.setIdentifiantExterieur(null);
                            adresseAMaj.setPorteurUid(null);
                        } else {
                            // On supprime l'identifiant externe pour ne pas synchroniser avec aia
                            adresseDto.setIdext(null);
                        }
                    }
                }
                final Adresse adresseCree = creerOuMettreAJourAdresse(personnes, adresseDto, impacterFamille);
                // on met l'id ext  jour apres la cration (probleme de flush a cause de la contrainte d'unicit)
                adresseCree.setIdentifiantExterieur(adresseDto.getIdext());
            }
        }
        final AdresseNature adresseNature = adresseNatureDao
                .rechercheAdresseNatureParId(squareMappingService.getIdNatureAdresseSecondaire());

        // si le rapport n'est pas en erreur, on met  jour l'adresse principale
        if (Boolean.FALSE.equals(rapportAdresses.getEnErreur())) {
            for (int i = 0; i < coordonnees.getAdresses().size(); i++) {
                final AdresseDto adresseDto = coordonnees.getAdresses().get(i);
                if (plusQueAdressePrincipale
                        && (adressePrincipaleEnCours.getId().equals(adresseDto.getIdentifiant()))) {
                    if (choixPasserEnSecondaire) {
                        adressePrincipaleEnCours.setNature(adresseNature);
                    } else {
                        dateFinAdressePrincipale.add(Calendar.DAY_OF_MONTH, -1);
                        adressePrincipaleEnCours.setDateFin(dateFinAdressePrincipale);
                    }
                    break;
                }
            }
        }
    }

    if (Boolean.TRUE.equals(rapportCoordonnees.getEnErreur())
            && !idNaturePersonneVivier.equals(idNaturePersonnePrincipale)
            && !idNaturePersonneBeneficiaireVivier.equals(idNaturePersonnePrincipale)) {
        RapportUtil.logRapport(rapportCoordonnees, logger);
        throw new ControleIntegriteException(rapportCoordonnees);
    }

    /*
     * // Un contact devra avoir au moins une adresse principal criteresRechercheAdressePrincipale = new AdresseCriteresRechercheDto();
     * criteresRechercheAdressePrincipale.setIdPersonne(personne.getId());
     * criteresRechercheAdressePrincipale.setIdNature(squareMappingService.getIdNatureAdressePrincipale()); long nbPrimaires =
     * adresseDao.rechercherIdAdressesParCriteres(criteresRechercheAdressePrincipale).size(); if (nbPrimaires == 0) { throw new
     * BusinessException(messageSourceUtil.get(PersonnePhysiqueKeyUtil.MESSAGE_ERREUR_AUCUNE_ADRESSE_PRINCIPALE)); } else if (nbPrimaires > 1) { throw new
     * BusinessException(messageSourceUtil.get(PersonnePhysiqueKeyUtil.MESSAGE_ERREUR_ADRESSE_PRINCIPALE_DUPLIQUEE)); }
     */

    // 2.13 Une date de fin ne pourra etre mis sur une adresse principal que s'il existe une adresse secondaire.
    // Dans ce cas l'adresse principal deviendra automatiquement secondaire et l'adresse secondaire deviendra principal
    Adresse adressePrincipale = null;
    Adresse adresseSecondaire = null;
    for (Adresse adresse : personnePrincipale.getAdresses()) {
        if (adresse.getNature().getId().equals(squareMappingService.getIdNatureAdressePrincipale())) {
            adressePrincipale = adresse;
        }
        if (adresse.getNature().getId().equals(squareMappingService.getIdNatureAdresseSecondaire())
                && adresse.getDateFin() == null) {
            adresseSecondaire = adresse;
        }
    }
    if (adressePrincipale != null && adressePrincipale.getDateFin() != null && adresseSecondaire != null) {
        // Changement adresse principale adresse secondaire
        adressePrincipale.setNature(adresseNatureDao
                .rechercheAdresseNatureParId(squareMappingService.getIdNatureAdresseSecondaire()));
        adresseSecondaire.setNature(adresseNatureDao
                .rechercheAdresseNatureParId(squareMappingService.getIdNatureAdressePrincipale()));
        // Enregistrement des adresses
        final AdresseDto adresseDtoPrincipal = mapperDozerBean.map(adressePrincipale, AdresseDto.class);
        final AdresseDto adresseDtoSecondaire = mapperDozerBean.map(adresseSecondaire, AdresseDto.class);
        creerOuMettreAJourAdresse(personnes, adresseDtoPrincipal, impacterFamille);
        creerOuMettreAJourAdresse(personnes, adresseDtoSecondaire, impacterFamille);
    }

    if (!idNaturePersonneVivier.equals(idNaturePersonnePrincipale)
            && !idNaturePersonneBeneficiaireVivier.equals(idNaturePersonnePrincipale)) {
        controlerPersonneAUneAdressePrincipale(personnePrincipale);
    }

    // si il s'agit d'une personne physique et vivier ou bnficiaire vivier, on transforme en prospect ou bnficiaire prospect
    boolean vivierToProspect = false;
    boolean hasNaturePersonneChanged = false;
    String ancienneNaturePersonne = "";
    String nouvelleNaturePersonne = "";
    if (personnePrincipalePhysique != null && personnePrincipalePhysique.getNature() != null) {
        ancienneNaturePersonne = personnePrincipalePhysique.getNature().getLibelle();
        Long idNaturePersonne = null;
        if (idNaturePersonneVivier.equals(idNaturePersonnePrincipale)
                && validationPersonneUtil.verifierContrainteProspect(personnePrincipalePhysique)) {
            idNaturePersonne = squareMappingService.getIdNaturePersonneProspect();
            vivierToProspect = true;
            hasNaturePersonneChanged = true;
        } else if (idNaturePersonneBeneficiaireVivier.equals(idNaturePersonnePrincipale)
                && validationPersonneUtil.verifierContrainteBeneficiaireProspect(personnePrincipalePhysique)) {
            idNaturePersonne = squareMappingService.getIdNaturePersonneBeneficiaireProspect();
            hasNaturePersonneChanged = true;
        }
        if (idNaturePersonne != null) {
            final PersonnePhysiqueNature naturePersonne = personnePhysiqueNatureDao
                    .rechercherPersonnePhysiqueParId(idNaturePersonne);
            if (naturePersonne != null) {
                nouvelleNaturePersonne = naturePersonne.getLibelle();
            }
            personnePrincipalePhysique.setNature(naturePersonne);
        }
    }

    // si la personne est passe de vivier  prospect et qu'elle a des bnficiaires vivier,
    // on essaye de les passer en bnficiaire prospect si c'est possible
    if (vivierToProspect && famille != null && famille.size() > 0) {
        for (Personne beneficiaire : famille) {
            final PersonnePhysique beneficiairePhysique = (PersonnePhysique) beneficiaire;
            if (beneficiairePhysique.getNature() != null
                    && idNaturePersonneBeneficiaireVivier.equals(beneficiairePhysique.getNature().getId())
                    && validationPersonneUtil.verifierContrainteBeneficiaireProspect(beneficiairePhysique)) {
                final PersonnePhysiqueNature naturePersonne = personnePhysiqueNatureDao
                        .rechercherPersonnePhysiqueParId(
                                squareMappingService.getIdNaturePersonneBeneficiaireProspect());
                beneficiairePhysique.setNature(naturePersonne);
            }
        }
    }

    final CoordonneesDto newCoordonnees = rechercherCoordonneesParIdPersonne(personnePrincipale.getId());
    newCoordonnees.setHasNaturePersonneChanged(hasNaturePersonneChanged);
    newCoordonnees.setAncienneNaturePersonne(ancienneNaturePersonne);
    newCoordonnees.setNouvelleNaturePersonne(nouvelleNaturePersonne);
    return newCoordonnees;
}

From source file:gov.nih.nci.cabig.caaers.rules.business.service.CaaersRulesEngineService.java

/**
 * Populates the ReadableRule and Readable actions in the given ruleset.
 * @param ruleSet - A cleaned ruleset/*from   w w  w .  j a  v a 2  s  .co  m*/
 */
//BJ : refactored, extracted from ReviewTab.referenceData():Map
public void makeRuleSetReadable(RuleSet ruleSet) {

    if (ruleSet == null || ruleSet.getRule() == null || ruleSet.getRule().size() <= 0)
        return;
    int i = 1;
    for (Rule rule : ruleSet.getRule()) {
        if (rule.isMarkedDelete())
            continue;

        //add the readable rules (LHS)
        ReadableRule readableRule = new ReadableRule();
        List<String> readableRuleLine = new ArrayList<String>();
        List<String> readableActions = new ArrayList<String>();

        readableRuleLine.add("If");

        if (rule.getCondition() != null && rule.getCondition().getColumn() != null) {
            int cCount = 0;
            for (Column column : rule.getCondition().getColumn()) {
                if (StringUtils.equals(column.getExpression(),
                        "getPrimaryFundingSponsorOrganization().getName()")
                        || StringUtils.equals(column.getObjectType(),
                                "gov.nih.nci.cabig.caaers.rules.common.AdverseEventEvaluationResult")
                        || StringUtils.equals(column.getObjectType(),
                                "com.semanticbits.rules.impl.RuleEvaluationResult")
                        || BooleanUtils.isTrue(column.isMarkedDelete()))
                    continue;

                if (cCount > 0)
                    readableRuleLine.add("And");
                readableRuleLine.add("   " + RuleUtil.readableColumn(column));
                cCount++;

            }
        }

        //add the readable actions (RHS)
        if (ruleSet.getDescription().equals(RuleType.MANDATORY_SECTIONS_RULES.getName())) {
            for (String action : rule.getAction())
                readableActions.add(ExpeditedReportSection.valueOf(action).getDisplayName());
        } else if (ruleSet.getDescription().equals(RuleType.FIELD_LEVEL_RULES.getName())) {
            for (String action : rule.getAction())
                readableActions.add(Mandatory.valueOf(action).getDisplayName());
        } else {
            readableActions.addAll(rule.getAction());
        }
        rule.getMetaData().setName("Rule-" + i);
        readableRule.setLine(readableRuleLine);
        rule.setReadableRule(readableRule);
        rule.setReadableAction(readableActions);

        i++;
    }

}

From source file:com.evolveum.midpoint.security.enforcer.impl.SecurityEnforcerImpl.java

private <O extends ObjectType> boolean isApplicable(SubjectedObjectSelectorType objectSelector,
        PrismObject<O> object, MidPointPrincipal principal, OwnerResolver ownerResolver, String desc,
        String autzHumanReadableDesc, Task task, OperationResult result)
        throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException,
        ConfigurationException, SecurityViolationException {
    ObjectFilterExpressionEvaluator filterExpressionEvaluator = createFilterEvaluator(principal, desc,
            autzHumanReadableDesc, task, result);
    if (!repositoryService.selectorMatches(objectSelector, object, filterExpressionEvaluator, LOGGER,
            "    " + autzHumanReadableDesc + " not applicable for " + desc + " because of")) {
        return false;
    }//from   ww  w. jav a  2s.  co  m

    OrgRelationObjectSpecificationType specOrgRelation = objectSelector.getOrgRelation();
    RoleRelationObjectSpecificationType specRoleRelation = objectSelector.getRoleRelation();

    // Special
    List<SpecialObjectSpecificationType> specSpecial = objectSelector.getSpecial();
    if (specSpecial != null && !specSpecial.isEmpty()) {
        if (objectSelector.getFilter() != null || objectSelector.getOrgRef() != null || specOrgRelation != null
                || specRoleRelation != null) {
            throw new SchemaException("Both filter/org/role and special " + desc
                    + " specification specified in " + autzHumanReadableDesc);
        }
        for (SpecialObjectSpecificationType special : specSpecial) {
            if (special == SpecialObjectSpecificationType.SELF) {
                String principalOid = principal != null ? principal.getOid() : null;
                if (principalOid == null) {
                    // This is a rare case. It should not normally happen. But it may happen in tests
                    // or during initial import. Therefore we are not going to die here. Just ignore it.
                } else {
                    if (principalOid.equals(object.getOid())) {
                        LOGGER.trace("    {}: 'self' authorization applicable for {}", autzHumanReadableDesc,
                                desc);
                        return true;
                    } else {
                        LOGGER.trace(
                                "    {}: 'self' authorization not applicable for {}, principal OID: {}, {} OID {}",
                                autzHumanReadableDesc, desc, principalOid, desc, object.getOid());
                    }
                }
            } else {
                throw new SchemaException("Unsupported special " + desc + " specification specified in "
                        + autzHumanReadableDesc + ": " + special);
            }
        }
        return false;
    } else {
        LOGGER.trace("    {}: specials empty: {}", autzHumanReadableDesc, specSpecial);
    }

    // orgRelation
    if (specOrgRelation != null) {
        boolean match = false;
        for (ObjectReferenceType subjectParentOrgRef : principal.getUser().getParentOrgRef()) {
            if (matchesOrgRelation(object, subjectParentOrgRef, specOrgRelation, autzHumanReadableDesc, desc)) {
                LOGGER.trace("    org {} applicable for {}, object OID {} because subject org {} matches",
                        autzHumanReadableDesc, desc, object.getOid(), subjectParentOrgRef.getOid());
                match = true;
                break;
            }
        }
        if (!match) {
            LOGGER.trace(
                    "    org {} not applicable for {}, object OID {} because none of the subject orgs matches",
                    autzHumanReadableDesc, desc, object.getOid());
            return false;
        }
    }

    // roleRelation
    if (specRoleRelation != null) {
        boolean match = false;
        for (ObjectReferenceType subjectRoleMembershipRef : principal.getUser().getRoleMembershipRef()) {
            if (matchesRoleRelation(object, subjectRoleMembershipRef, specRoleRelation, autzHumanReadableDesc,
                    desc)) {
                LOGGER.trace("    {} applicable for {}, object OID {} because subject role relation {} matches",
                        autzHumanReadableDesc, desc, object.getOid(), subjectRoleMembershipRef.getOid());
                match = true;
                break;
            }
        }
        if (!match) {
            LOGGER.trace(
                    "    {} not applicable for {}, object OID {} because none of the subject roles matches",
                    autzHumanReadableDesc, desc, object.getOid());
            return false;
        }
    }

    if (objectSelector instanceof OwnedObjectSelectorType) {
        // Owner
        SubjectedObjectSelectorType ownerSpec = ((OwnedObjectSelectorType) objectSelector).getOwner();
        if (ownerSpec != null) {
            if (ownerResolver == null) {
                ownerResolver = securityContextManager.getUserProfileService();
                if (ownerResolver == null) {
                    LOGGER.trace(
                            "    {}: owner object spec not applicable for {}, object OID {} because there is no owner resolver",
                            autzHumanReadableDesc, desc, object.getOid());
                    return false;
                }
            }
            PrismObject<? extends FocusType> owner = ownerResolver.resolveOwner(object);
            if (owner == null) {
                LOGGER.trace(
                        "    {}: owner object spec not applicable for {}, object OID {} because it has no owner",
                        autzHumanReadableDesc, desc, object.getOid());
                return false;
            }
            boolean ownerApplicable = isApplicable(ownerSpec, owner, principal, ownerResolver,
                    "owner of " + desc, autzHumanReadableDesc, task, result);
            if (!ownerApplicable) {
                LOGGER.trace(
                        "    {}: owner object spec not applicable for {}, object OID {} because owner does not match (owner={})",
                        autzHumanReadableDesc, desc, object.getOid(), owner);
                return false;
            }
        }

        // Delegator
        SubjectedObjectSelectorType delegatorSpec = ((OwnedObjectSelectorType) objectSelector).getDelegator();
        if (delegatorSpec != null) {
            if (!isSelf(delegatorSpec)) {
                throw new SchemaException("Unsupported non-self delegator clause");
            }
            if (!object.canRepresent(UserType.class)) {
                LOGGER.trace(
                        "    {}: delegator object spec not applicable for {}, because the object is not user",
                        autzHumanReadableDesc, desc);
                return false;
            }
            boolean found = false;
            for (ObjectReferenceType objectDelegatedRef : ((UserType) object.asObjectable())
                    .getDelegatedRef()) {
                if (principal.getOid().equals(objectDelegatedRef.getOid())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                if (BooleanUtils.isTrue(delegatorSpec.isAllowInactive())) {
                    for (AssignmentType objectAssignment : ((UserType) object.asObjectable()).getAssignment()) {
                        ObjectReferenceType objectAssignmentTargetRef = objectAssignment.getTargetRef();
                        if (objectAssignmentTargetRef == null) {
                            continue;
                        }
                        if (principal.getOid().equals(objectAssignmentTargetRef.getOid())) {
                            if (QNameUtil.match(SchemaConstants.ORG_DEPUTY,
                                    objectAssignmentTargetRef.getRelation())) {
                                found = true;
                                break;
                            }
                        }
                    }
                }

                if (!found) {
                    LOGGER.trace(
                            "    {}: delegator object spec not applicable for {}, object OID {} because delegator does not match",
                            autzHumanReadableDesc, desc, object.getOid());
                    return false;
                }
            }

        }
    }

    LOGGER.trace("    {} applicable for {} (filter)", autzHumanReadableDesc, desc);
    return true;
}

From source file:com.haulmont.cuba.web.gui.components.WebAbstractTable.java

@Override
public void setDatasource(final CollectionDatasource datasource) {
    Preconditions.checkNotNullArgument(datasource, "datasource is null");

    if (this.datasource != null) {
        if (!this.datasource.getMetaClass().equals(datasource.getMetaClass())) {
            throw new IllegalArgumentException("The new datasource must correspond to the same MetaClass");
        }//  w  ww.j a v  a2  s .co m

        if (fieldDatasources != null) {
            fieldDatasources.clear();
        }

        if (collectionDsListenersWrapper != null) {
            collectionDsListenersWrapper.unbind(this.datasource);
            if (containerDatasource != null) {
                containerDatasource.unsubscribe();
                containerDatasource = null;
            }
        }
    }

    MessageTools messageTools = AppBeans.get(MessageTools.NAME);

    final Collection<Object> columns;
    if (this.columns.isEmpty()) {
        Collection<MetaPropertyPath> paths = datasource.getView() != null ?
        // if a view is specified - use view properties
                metadataTools.getViewPropertyPaths(datasource.getView(), datasource.getMetaClass()) :
                // otherwise use all properties from meta-class
                metadataTools.getPropertyPaths(datasource.getMetaClass());
        for (MetaPropertyPath metaPropertyPath : paths) {
            MetaProperty property = metaPropertyPath.getMetaProperty();
            if (!property.getRange().getCardinality().isMany() && !metadataTools.isSystem(property)) {
                Table.Column column = new Table.Column(metaPropertyPath);

                String propertyName = property.getName();
                MetaClass propertyMetaClass = metadataTools.getPropertyEnclosingMetaClass(metaPropertyPath);

                column.setCaption(messageTools.getPropertyCaption(propertyMetaClass, propertyName));
                column.setType(metaPropertyPath.getRangeJavaClass());

                Element element = DocumentHelper.createElement("column");
                column.setXmlDescriptor(element);

                addColumn(column);
            }
        }
    }
    columns = this.columns.keySet();

    this.datasource = datasource;

    if (collectionDsListenersWrapper == null) {
        collectionDsListenersWrapper = createCollectionDsListenersWrapper();
    }

    containerDatasource = createContainerDatasource(datasource, getPropertyColumns(),
            collectionDsListenersWrapper);

    component.setContainerDataSource(containerDatasource);

    List<MetaPropertyPath> editableColumns = null;
    if (isEditable()) {
        editableColumns = new LinkedList<>();
    }

    MetaClass metaClass = datasource.getMetaClass();
    for (final Object columnId : columns) {
        final Table.Column column = this.columns.get(columnId);

        final String caption;
        if (column != null) {
            caption = getColumnCaption(columnId, column);
        } else {
            caption = StringUtils.capitalize(getColumnCaption(columnId));
        }

        setColumnHeader(columnId, caption);

        if (column != null) {
            if (editableColumns != null && column.isEditable() && (columnId instanceof MetaPropertyPath)) {
                MetaPropertyPath propertyPath = ((MetaPropertyPath) columnId);
                if (security.isEntityAttrUpdatePermitted(metaClass, propertyPath.toString())) {
                    editableColumns.add(propertyPath);
                }
            }

            if (column.isCollapsed() && component.isColumnCollapsingAllowed()) {
                if (!(columnId instanceof MetaPropertyPath)
                        || security.isEntityAttrReadPermitted(metaClass, columnId.toString())) {
                    component.setColumnCollapsed(column.getId(), true);
                }
            }

            if (column.getAggregation() != null && isAggregatable()) {
                checkAggregation(column.getAggregation());

                component.addContainerPropertyAggregation(column.getId(),
                        WebComponentsHelper.convertAggregationType(column.getAggregation().getType()));
            }
        }
    }

    if (editableColumns != null && !editableColumns.isEmpty()) {
        setEditableColumns(editableColumns);
    }

    createColumns(containerDatasource);

    for (Table.Column column : this.columnsOrder) {
        if (editable && column.getAggregation() != null
                && (BooleanUtils.isTrue(column.isEditable()) || BooleanUtils.isTrue(column.isCalculatable()))) {
            addAggregationCell(column);
        }
    }

    createStubsForGeneratedColumns();

    setVisibleColumns(getInitialVisibleColumns());

    if (security.isSpecificPermitted(ShowInfoAction.ACTION_PERMISSION)) {
        ShowInfoAction action = (ShowInfoAction) getAction(ShowInfoAction.ACTION_ID);
        if (action == null) {
            action = new ShowInfoAction();
            addAction(action);
        }
        action.setDatasource(datasource);
    }

    if (rowsCount != null) {
        rowsCount.setDatasource(datasource);
    }

    collectionDsListenersWrapper.bind(datasource);

    for (Action action : getActions()) {
        action.refreshState();
    }

    if (!canBeSorted(datasource))
        setSortable(false);

    assignAutoDebugId();
}

From source file:jp.primecloud.auto.service.impl.ComponentServiceImpl.java

/**
 * {@inheritDoc}/*from w w  w. j  av a2s . com*/
 */
@Override
public ComponentTypeDto getComponentType(Long componentNo) {
    // ????
    Component component = componentDao.read(componentNo);

    // ????
    ComponentType componentType = componentTypeDao.read(component.getComponentTypeNo());

    // ?
    List<Instance> instances = new ArrayList<Instance>();
    List<Instance> allInstances = instanceDao.readByFarmNo(component.getFarmNo());
    for (Instance instance : allInstances) {
        // ?
        if (BooleanUtils.isTrue(instance.getLoadBalancer())) {
            continue;
        }

        instances.add(instance);
    }

    // ????
    List<Component> components = componentDao.readByFarmNo(component.getFarmNo());

    // ?
    List<Long> availableInstanceNos = new ArrayList<Long>();

    // ??????
    for (Instance instance : instances) {
        Image image = imageDao.read(instance.getImageNo());
        String[] componentTypeNos = StringUtils.split(image.getComponentTypeNos(), ",");
        boolean available = false;
        for (String componentTypeNo : componentTypeNos) {
            if (componentType.getComponentTypeNo().equals(Long.parseLong(componentTypeNo.trim()))) {
                available = true;
                break;
            }
        }
        if (available) {
            availableInstanceNos.add(instance.getInstanceNo());
        }
    }

    // ??????????????????????????
    for (Component component2 : components) {
        if (componentNo.equals(component2.getComponentNo())) {
            continue;
        }
        ComponentType componentType2 = componentTypeDao.read(component2.getComponentTypeNo());
        if (StringUtils.equals(componentType.getLayer(), componentType2.getLayer())) {
            List<ComponentInstance> componentInstances = componentInstanceDao
                    .readByComponentNo(component2.getComponentNo());
            for (ComponentInstance componentInstance : componentInstances) {
                ComponentInstanceStatus status = ComponentInstanceStatus
                        .fromStatus(componentInstance.getStatus());
                if (BooleanUtils.isTrue(componentInstance.getAssociate())
                        || status != ComponentInstanceStatus.STOPPED) {
                    availableInstanceNos.remove(componentInstance.getInstanceNo());
                }
            }
        }
    }

    // DTO??
    ComponentTypeDto dto = new ComponentTypeDto();
    dto.setComponentType(componentType);
    dto.setInstanceNos(availableInstanceNos);

    return dto;
}

From source file:com.evolveum.midpoint.provisioning.impl.ShadowManager.java

public String addNewProposedShadow(ProvisioningContext ctx, PrismObject<ShadowType> shadow, Task task,
        OperationResult result) throws ObjectNotFoundException, SchemaException, CommunicationException,
        ConfigurationException, ExpressionEvaluationException, ObjectAlreadyExistsException,
        SecurityViolationException, EncryptionException {
    ResourceConsistencyType consistency = ctx.getResource().getConsistency();
    if (consistency == null) {
        return null;
    }//ww  w. j  a v  a 2  s . c o  m
    if (!BooleanUtils.isTrue(consistency.isUseProposedShadows())) {
        return null;
    }

    PrismObject<ShadowType> repoShadow = createRepositoryShadow(ctx, shadow);
    repoShadow.asObjectable().setLifecycleState(SchemaConstants.LIFECYCLE_PROPOSED);
    addPendingOperationAdd(repoShadow, shadow, PendingOperationExecutionStatusType.REQUESTED, null,
            task.getTaskIdentifier());

    ConstraintsChecker.onShadowAddOperation(repoShadow.asObjectable());
    String oid = repositoryService.addObject(repoShadow, null, result);
    LOGGER.trace("Proposed shadow added to the repository: {}", repoShadow);
    return oid;
}

From source file:com.evolveum.midpoint.security.enforcer.impl.SecurityEnforcerImpl.java

private <O extends ObjectType> boolean matchesOrgRelation(PrismObject<O> object,
        ObjectReferenceType subjectParentOrgRef, OrgRelationObjectSpecificationType specOrgRelation,
        String autzHumanReadableDesc, String desc) throws SchemaException {
    if (!MiscSchemaUtil.compareRelation(specOrgRelation.getSubjectRelation(),
            subjectParentOrgRef.getRelation())) {
        return false;
    }/*from  w  w w . j ava  2 s  .  co  m*/
    if (BooleanUtils.isTrue(specOrgRelation.isIncludeReferenceOrg())
            && subjectParentOrgRef.getOid().equals(object.getOid())) {
        return true;
    }
    if (specOrgRelation.getScope() == null) {
        return repositoryService.isDescendant(object, subjectParentOrgRef.getOid());
    }
    switch (specOrgRelation.getScope()) {
    case ALL_DESCENDANTS:
        return repositoryService.isDescendant(object, subjectParentOrgRef.getOid());
    case DIRECT_DESCENDANTS:
        return hasParentOrgRef(object, subjectParentOrgRef.getOid());
    case ALL_ANCESTORS:
        return repositoryService.isAncestor(object, subjectParentOrgRef.getOid());
    default:
        throw new UnsupportedOperationException("Unknown orgRelation scope " + specOrgRelation.getScope());
    }
}

From source file:jp.primecloud.auto.service.impl.ComponentServiceImpl.java

/**
 * {@inheritDoc}// ww  w.j av  a 2  s .c o m
 */
@Override
public void deleteComponent(Long componentNo) {
    // ?
    if (componentNo == null) {
        throw new AutoApplicationException("ECOMMON-000003", "componentNo");
    }

    // ????
    Component component = componentDao.read(componentNo);
    if (component == null) {
        // ???????
        return;
    }

    // ?????????????
    List<ComponentInstance> componentInstances = componentInstanceDao.readByComponentNo(componentNo);
    for (ComponentInstance componentInstance : componentInstances) {
        ComponentInstanceStatus status = ComponentInstanceStatus.fromStatus(componentInstance.getStatus());
        if (status != ComponentInstanceStatus.STOPPED) {
            // ????????
            throw new AutoApplicationException("ESERVICE-000302", component.getComponentName());
        }
    }

    // ???????????
    List<AwsVolume> awsVolumes = awsVolumeDao.readByComponentNo(componentNo);
    for (AwsVolume awsVolume : awsVolumes) {
        if (StringUtils.isNotEmpty(awsVolume.getInstanceId())) {
            // ????????
            Instance instance = instanceDao.read(awsVolume.getInstanceNo());
            throw new AutoApplicationException("ESERVICE-000310", instance.getInstanceName());
        }
    }
    // ???????????
    List<CloudstackVolume> csVolumes = cloudstackVolumeDao.readByComponentNo(componentNo);
    for (CloudstackVolume csVolume : csVolumes) {
        if (StringUtils.isNotEmpty(csVolume.getInstanceId())) {
            // ????????
            Instance instance = instanceDao.read(csVolume.getInstanceNo());
            throw new AutoApplicationException("ESERVICE-000310", instance.getInstanceName());
        }
    }
    List<VmwareDisk> vmwareDisks = vmwareDiskDao.readByComponentNo(componentNo);
    for (VmwareDisk vmwareDisk : vmwareDisks) {
        if (BooleanUtils.isTrue(vmwareDisk.getAttached())) {
            // ????????
            Instance instance = instanceDao.read(vmwareDisk.getInstanceNo());
            throw new AutoApplicationException("ESERVICE-000310", instance.getInstanceName());
        }
    }
    List<VcloudDisk> vcloudDisks = vcloudDiskDao.readByComponentNo(componentNo);
    for (VcloudDisk vcloudDisk : vcloudDisks) {
        if (BooleanUtils.isTrue(vcloudDisk.getAttached())) {
            // Vcloud????????????????????????
            Instance instance = instanceDao.read(vcloudDisk.getInstanceNo());
            InstanceStatus status = InstanceStatus.fromStatus(instance.getStatus());
            if (InstanceStatus.STOPPED != status) {
                throw new AutoApplicationException("ESERVICE-000310", instance.getInstanceName());
            }
        }
    }
    // ???????????
    List<AzureDisk> azureDisks = azureDiskDao.readByComponentNo(componentNo);
    for (AzureDisk azureDisk : azureDisks) {
        if (StringUtils.isNotEmpty(azureDisk.getInstanceName())) {
            // ????????
            Instance instance = instanceDao.read(azureDisk.getInstanceNo());
            throw new AutoApplicationException("ESERVICE-000310", instance.getInstanceName());
        }
    }
    // ???????????
    List<OpenstackVolume> osVolumes = openstackVolumeDao.readByComponentNo(componentNo);
    for (OpenstackVolume osVolume : osVolumes) {
        if (StringUtils.isNotEmpty(osVolume.getInstanceId())) {
            // ????????
            Instance instance = instanceDao.read(osVolume.getInstanceNo());
            throw new AutoApplicationException("ESERVICE-000310", instance.getInstanceName());
        }
    }
    // ???????????
    List<NiftyVolume> niftyVolumes = niftyVolumeDao.readByComponentNo(componentNo);
    for (NiftyVolume niftyVolume : niftyVolumes) {
        if (StringUtils.isNotEmpty(niftyVolume.getInstanceId())) {
            // ????????
            Instance instance = instanceDao.read(niftyVolume.getInstanceNo());
            throw new AutoApplicationException("ESERVICE-000310", instance.getInstanceName());
        }
    }

    // ???????????????
    List<LoadBalancer> loadBalancers = loadBalancerDao.readByComponentNo(componentNo);
    if (!loadBalancers.isEmpty()) {
        throw new AutoApplicationException("ESERVICE-000309", loadBalancers.get(0).getLoadBalancerName());
    }

    // ??
    instanceConfigDao.deleteByComponentNo(componentNo);

    // ??????
    doAssociate(componentNo, new ArrayList<Long>());
    componentInstanceDao.deleteByComponentNo(componentNo);

    // ????
    componentConfigDao.deleteByComponentNo(componentNo);

    // ???
    // TODO CLOUD BRANCHING
    Farm farm = farmDao.read(component.getFarmNo());

    // AWS??
    // TODO: ???????
    for (AwsVolume awsVolume : awsVolumes) {
        if (StringUtils.isEmpty(awsVolume.getVolumeId())) {
            continue;
        }

        IaasGatewayWrapper gateway = iaasGatewayFactory.createIaasGateway(farm.getUserNo(),
                awsVolume.getPlatformNo());

        //
        Platform platform = platformDao.read(gateway.getPlatformNo());
        Instance instance = instanceDao.read(awsVolume.getInstanceNo());
        AwsInstance awsInstance = awsInstanceDao.read(awsVolume.getInstanceNo());
        eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(), awsVolume.getComponentNo(),
                component.getComponentName(), awsVolume.getInstanceNo(), instance.getInstanceName(),
                "AwsEbsDelete", awsInstance.getInstanceType(), instance.getPlatformNo(),
                new Object[] { platform.getPlatformName(), awsVolume.getVolumeId() });

        try {
            // ?
            gateway.deleteVolume(awsVolume.getVolumeId());

            //
            eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(),
                    awsVolume.getComponentNo(), component.getComponentName(), awsVolume.getInstanceNo(),
                    instance.getInstanceName(), "AwsEbsDeleteFinish", awsInstance.getInstanceType(),
                    instance.getPlatformNo(),
                    new Object[] { platform.getPlatformName(), awsVolume.getVolumeId() });

            // EC2??DeleteVolume???????Wait???
            //awsProcessClient.waitDeleteVolume(volumeId);
        } catch (AutoException ignore) {
            // ??????????????
        }
    }
    awsVolumeDao.deleteByComponentNo(componentNo);

    // CLOUDSTACK??
    // TODO: ???????
    for (CloudstackVolume csVolume : csVolumes) {
        if (StringUtils.isEmpty(csVolume.getVolumeId())) {
            continue;
        }

        IaasGatewayWrapper gateway = iaasGatewayFactory.createIaasGateway(farm.getUserNo(),
                csVolume.getPlatformNo());

        //
        Platform platform = platformDao.read(gateway.getPlatformNo());
        Instance instance = instanceDao.read(csVolume.getInstanceNo());
        CloudstackInstance csInstance = cloudstackInstanceDao.read(csVolume.getInstanceNo());
        eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(), csVolume.getComponentNo(),
                component.getComponentName(), csVolume.getInstanceNo(), instance.getInstanceName(),
                "CloudStackVolumeDelete", csInstance.getInstanceType(), instance.getPlatformNo(),
                new Object[] { platform.getPlatformName(), csVolume.getVolumeId() });

        try {
            // ?
            gateway.deleteVolume(csVolume.getVolumeId());

            //
            eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(),
                    csVolume.getComponentNo(), component.getComponentName(), csVolume.getInstanceNo(),
                    instance.getInstanceName(), "CloudStackVolumeDeleteFinish", csInstance.getInstanceType(),
                    instance.getPlatformNo(),
                    new Object[] { platform.getPlatformName(), csVolume.getVolumeId() });

        } catch (AutoException ignore) {
            // ??????????????
        }
    }
    cloudstackVolumeDao.deleteByComponentNo(componentNo);

    // VMware??
    // TODO: ??????
    for (VmwareDisk vmwareDisk : vmwareDisks) {
        if (StringUtils.isEmpty(vmwareDisk.getFileName())) {
            continue;
        }
        VmwareProcessClient vmwareProcessClient = vmwareProcessClientFactory
                .createVmwareProcessClient(vmwareDisk.getPlatformNo());
        try {
            vmwareDiskProcess.deleteDisk(vmwareProcessClient, vmwareDisk.getDiskNo());
        } catch (AutoException ignore) {
            // ??????????????
        } finally {
            vmwareProcessClient.getVmwareClient().logout();
        }
    }
    vmwareDiskDao.deleteByComponentNo(componentNo);

    // VCloud??
    // VCLoud????doAssociate?????
    //        for (VcloudDisk vcloudDisk : vcloudDisks) {
    //            if (StringUtils.isEmpty(vcloudDisk.getDiskId())) {
    //                continue;
    //            }
    //
    //            IaasGatewayWrapper gateway = iaasGatewayFactory.createIaasGateway(farm.getUserNo(), vcloudDisk.getPlatformNo());
    //
    //            //
    //            Platform platform = platformDao.read(gateway.getPlatformNo());
    //            Instance instance = instanceDao.read(vcloudDisk.getInstanceNo());
    //            VcloudInstance vcloudInstance = vcloudInstanceDao.read(vcloudDisk.getInstanceNo());
    //            //TODO ??
    //            eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(), vcloudDisk.getComponentNo(),
    //                    component.getComponentName(), vcloudDisk.getInstanceNo(), instance.getInstanceName(),
    //                    "VcloudVolumeDelete", vcloudInstance.getInstanceType(),  instance.getPlatformNo(), new Object[] { platform.getPlatformName(), vcloudDisk.getDiskId() });
    //
    //            try {
    //                // ?
    //                // VCloud??DiskNo
    //                gateway.deleteVolume(String.valueOf(vcloudDisk.getDiskNo()));
    //
    //                //
    //                eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(), vcloudDisk.getComponentNo(),
    //                        component.getComponentName(), vcloudDisk.getInstanceNo(), instance.getInstanceName(),
    //                        "VcloudVolumeDeleteFinish", vcloudInstance.getInstanceType(), instance.getPlatformNo(), new Object[] { platform.getPlatformName(), vcloudDisk.getDiskId() });
    //
    //            } catch (AutoException ignore) {
    //                // ??????????????
    //            }
    //        }
    //        vcloudDiskDao.deleteByComponentNo(componentNo);

    // Azure??
    // TODO: ???????
    for (AzureDisk azureDisk : azureDisks) {
        if (StringUtils.isEmpty(azureDisk.getDiskName())) {
            continue;
        }

        IaasGatewayWrapper gateway = iaasGatewayFactory.createIaasGateway(farm.getUserNo(),
                azureDisk.getPlatformNo());

        //
        Platform platform = platformDao.read(gateway.getPlatformNo());
        Instance instance = instanceDao.read(azureDisk.getInstanceNo());
        AzureInstance azureInstance = azureInstanceDao.read(azureDisk.getInstanceNo());
        eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(), azureDisk.getComponentNo(),
                component.getComponentName(), azureDisk.getInstanceNo(), instance.getInstanceName(),
                "AzureDiskDelete", azureInstance.getInstanceType(), instance.getPlatformNo(),
                new Object[] { platform.getPlatformName(), azureDisk.getDiskName() });

        try {
            // ?
            gateway.deleteVolume(azureDisk.getDiskNo().toString());

            //
            eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(),
                    azureDisk.getComponentNo(), component.getComponentName(), azureDisk.getInstanceNo(),
                    instance.getInstanceName(), "AzureDiskDeleteFinish", azureInstance.getInstanceType(),
                    instance.getPlatformNo(),
                    new Object[] { platform.getPlatformName(), azureDisk.getDiskName() });

        } catch (AutoException ignore) {
            // ??????????????
        }
    }
    azureDiskDao.deleteByComponentNo(componentNo);

    // Openstack??
    // TODO: ???????
    for (OpenstackVolume osVolume : osVolumes) {
        if (StringUtils.isEmpty(osVolume.getVolumeId())) {
            continue;
        }

        IaasGatewayWrapper gateway = iaasGatewayFactory.createIaasGateway(farm.getUserNo(),
                osVolume.getPlatformNo());

        //
        Platform platform = platformDao.read(gateway.getPlatformNo());
        Instance instance = instanceDao.read(osVolume.getInstanceNo());
        OpenstackInstance osInstance = openstackInstanceDao.read(osVolume.getInstanceNo());
        eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(), osVolume.getComponentNo(),
                component.getComponentName(), osVolume.getInstanceNo(), instance.getInstanceName(),
                "OpenstackVolumeDelete", osInstance.getInstanceType(), instance.getPlatformNo(),
                new Object[] { platform.getPlatformName(), osVolume.getVolumeId() });

        try {
            // ?
            gateway.deleteVolume(osVolume.getVolumeId());

            //
            eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(),
                    osVolume.getComponentNo(), component.getComponentName(), osVolume.getInstanceNo(),
                    instance.getInstanceName(), "OpenstackVolumeDeleteFinish", osInstance.getInstanceType(),
                    instance.getPlatformNo(),
                    new Object[] { platform.getPlatformName(), osVolume.getVolumeId() });

        } catch (AutoException ignore) {
            // ??????????????
        }
    }
    openstackVolumeDao.deleteByComponentNo(componentNo);

    // Nifty??
    // TODO: ???????
    for (NiftyVolume niftyVolume : niftyVolumes) {
        if (StringUtils.isEmpty(niftyVolume.getVolumeId())) {
            continue;
        }

        // NiftyProcessClient??
        String clientType;
        clientType = PCCConstant.NIFTYCLIENT_TYPE_DISK;
        NiftyProcessClient niftyProcessClient = niftyProcessClientFactory
                .createNiftyProcessClient(farm.getUserNo(), niftyVolume.getPlatformNo(), clientType);

        //
        Platform platform = platformDao.read(niftyProcessClient.getPlatformNo());
        Instance instance = instanceDao.read(niftyVolume.getInstanceNo());
        NiftyInstance niftyInstance = niftyInstanceDao.read(niftyVolume.getInstanceNo());
        eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(), niftyVolume.getComponentNo(),
                component.getComponentName(), niftyVolume.getInstanceNo(), instance.getInstanceName(),
                "NiftyDiskDelete", niftyInstance.getInstanceType(), instance.getPlatformNo(),
                new Object[] { platform.getPlatformName(), niftyVolume.getVolumeId() });

        try {
            // ?
            niftyProcessClient.deleteVolume(niftyVolume.getVolumeId());

            //
            eventLogger.log(EventLogLevel.DEBUG, farm.getFarmNo(), farm.getFarmName(),
                    niftyVolume.getComponentNo(), component.getComponentName(), niftyVolume.getInstanceNo(),
                    instance.getInstanceName(), "NiftyDiskDeleteFinish", niftyInstance.getInstanceType(),
                    instance.getPlatformNo(),
                    new Object[] { platform.getPlatformName(), niftyVolume.getVolumeId() });

        } catch (AutoException ignore) {
            // ??????????????
        }
    }
    niftyVolumeDao.deleteByComponentNo(componentNo);

    // ????
    componentDao.delete(component);

    // 
    StringBuilder dpath = new StringBuilder("/opt/userdata/");
    dpath.append(LoggingUtils.getUserName());
    dpath.append(System.getProperty("file.separator"));
    dpath.append(LoggingUtils.getFarmName());
    dpath.append(System.getProperty("file.separator"));
    dpath.append(component.getComponentName());
    File delDir = new File(dpath.toString());
    if (delDir.exists()) {
        deleteDirectoryAndFile(delDir);
    }

    // 
    eventLogger.log(EventLogLevel.INFO, farm.getFarmNo(), farm.getFarmName(), componentNo,
            component.getComponentName(), null, null, "ComponentDelete", null, null, null);
}