Example usage for java.util HashSet addAll

List of usage examples for java.util HashSet addAll

Introduction

In this page you can find the example usage for java.util HashSet addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:it.cnr.icar.eric.common.BindingUtility.java

/**
 * Gets the Set of ReferenceInfo for all object references within specified RegistryObject.
 * TODO: replace with reflections API when JAXB bindings use special class for ReferenceURI.
 *
 * Reference attributes based on scanning rim.xsd for anyURI.
 *
 * @param ro specifies the RegistryObject whose ObjectRefs are being sought.
 *
 * @param idMap The Map with old temporary id to new permanent id mapping.
 *
 *//*  w ww  . j  ava  2 s. c  om*/
public Set<ReferenceInfo> getObjectRefsInRegistryObject(RegistryObjectType ro, Map<?, ?> idMap,
        Set<RegistryObjectType> processedObjects, int depth) throws JAXRException {
    HashSet<ReferenceInfo> refInfos = new HashSet<ReferenceInfo>();

    if ((ro != null) && (!processedObjects.contains(ro))) {
        processedObjects.add(ro);
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.RegistryObjectType", refInfos, idMap,
                "ObjectType");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ClassificationNodeType", refInfos, idMap,
                "Parent");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ClassificationType", refInfos, idMap,
                "ClassificationNode");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ClassificationType", refInfos, idMap,
                "ClassificationScheme");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ClassificationType", refInfos, idMap,
                "ClassifiedObject");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ExternalIdentifierType", refInfos, idMap,
                "IdentificationScheme");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ExternalIdentifierType", refInfos, idMap,
                "RegistryObject");

        //FederationType fed = (FederationType)ro;
        //TODO: Fix so it adds only Strings not ObjectRefType
        //refInfos.addAll(fed.getMembers().getObjectRef());

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AssociationType1", refInfos, idMap,
                "AssociationType");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AssociationType1", refInfos, idMap,
                "SourceObject");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AssociationType1", refInfos, idMap,
                "TargetObject");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AuditableEventType", refInfos, idMap,
                "User");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.AuditableEventType", refInfos, idMap,
                "RequestId");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.OrganizationType", refInfos, idMap,
                "Parent");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.RegistryType", refInfos, idMap,
                "Operator");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ServiceBindingType", refInfos, idMap,
                "Service");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.ServiceBindingType", refInfos, idMap,
                "TargetBinding");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.SpecificationLinkType", refInfos, idMap,
                "ServiceBinding");
        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.SpecificationLinkType", refInfos, idMap,
                "SpecificationObject");

        processRefAttribute(ro, "org.oasis.ebxml.registry.bindings.rim.SubscriptionType", refInfos, idMap,
                "Selector");

        --depth;

        //Now process composed objects
        if (depth != 0) {
            Set<RegistryObjectType> composedObjects = getComposedRegistryObjects(ro, 1);
            Iterator<RegistryObjectType> iter = composedObjects.iterator();
            while (iter.hasNext()) {
                Object obj = iter.next();
                if (obj instanceof RegistryObjectType) {
                    RegistryObjectType composedObject = (RegistryObjectType) obj;
                    Set<ReferenceInfo> composedRefInfos = getObjectRefsInRegistryObject(composedObject, idMap,
                            processedObjects, depth);
                    refInfos.addAll(composedRefInfos);
                }
            }
        }
    }

    return refInfos;
}

From source file:org.cgiar.ccafs.marlo.action.summaries.ReportingSummaryAction.java

private TypedTableModel getDeliverablesReportingTableModel() {
    TypedTableModel model = new TypedTableModel(new String[] { "deliverable_id", "title", "deliv_type",
            "deliv_sub_type", "deliv_status", "deliv_year", "key_output", "leader", "institution",
            "funding_sources", "cross_cutting", "deliv_new_year", "deliv_new_year_justification",
            "deliv_dissemination_channel", "deliv_dissemination_url", "deliv_open_access", "deliv_license",
            "titleMetadata", "descriptionMetadata", "dateMetadata", "languageMetadata", "countryMetadata",
            "keywordsMetadata", "citationMetadata", "HandleMetadata", "DOIMetadata", "creator_authors",
            "data_sharing", "qualityAssurance", "dataDictionary", "tools", "showFAIR", "F", "A", "I", "R",
            "isDisseminated", "disseminated", "restricted_access", "isRestricted", "restricted_date",
            "isLastTwoRestricted", "deliv_license_modifications", "show_deliv_license_modifications", "volume",
            "issue", "pages", "journal", "journal_indicators", "acknowledge", "fl_contrib", "show_publication",
            "showCompilance", "deliv_description", "hasIntellectualAsset", "isPantent", "isPvp",
            "hasParticipants", "isAcademicDegree", "isRegional", "isNational", "hasParticipantsText",
            "participantEvent", "participantActivityType", "participantAcademicDegree",
            "participantTotalParticipants", "participantFemales", "participantType",
            "participantGeographicScope", "participantRegional", "participantCountries",
            "hasIntellectualAssetText", "intellectualAssetApplicants", "intellectualAssetType",
            "intellectualAssetTitle", "intellectualAssetFillingType", "intellectualAssetPantentStatus",
            "intellectualAssetPatentType", "intellectualAssetPvpVarietyName", "intellectualAssetPvpStatus",
            "intellectualAssetPvpCountry", "intellectualAssetPvpApplicationNumber",
            "intellectualAssetPvpBreederCrop", "intellectualAssetDateFilling",
            "intellectualAssetDateRegistration", "intellectualAssetDateExpiry",
            "intellectualAssetAdditionalInformation", "intellectualAssetLinkPublished",
            "intellectualAssetCommunication" },
            new Class[] { Long.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, Boolean.class, String.class, String.class, String.class, String.class,
                    Boolean.class, String.class, String.class, Boolean.class, String.class, Boolean.class,
                    String.class, Boolean.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, Boolean.class, Boolean.class, String.class,
                    Boolean.class, Boolean.class, Boolean.class, Boolean.class, Boolean.class, Boolean.class,
                    Boolean.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class, String.class,
                    String.class, String.class, String.class, String.class, String.class },
            0);//from   w ww .ja  va2  s. c  o m
    SimpleDateFormat formatter = new SimpleDateFormat("MMM yyyy");
    if (!project.getDeliverables().isEmpty()) {
        // get Reporting deliverables
        List<Deliverable> deliverables = project.getDeliverables().stream().filter(d -> d.isActive()
                && d.getProject() != null && d.getProject().isActive()
                && d.getProject().getGlobalUnitProjects().stream()
                        .filter(gup -> gup.isActive()
                                && gup.getGlobalUnit().getId().equals(this.getLoggedCrp().getId()))
                        .collect(Collectors.toList()).size() > 0
                && d.getDeliverableInfo(this.getSelectedPhase()) != null
                && d.getDeliverableInfo(this.getSelectedPhase()).getStatus() != null
                && ((d.getDeliverableInfo(this.getSelectedPhase()).getStatus().intValue() == Integer
                        .parseInt(ProjectStatusEnum.Complete.getStatusId())
                        && (d.getDeliverableInfo(this.getSelectedPhase()).getYear() >= this.getSelectedYear()
                                || (d.getDeliverableInfo(this.getSelectedPhase()).getNewExpectedYear() != null
                                        && d.getDeliverableInfo(this.getSelectedPhase()).getNewExpectedYear()
                                                .intValue() >= this.getSelectedYear())))
                        || (d.getDeliverableInfo(this.getSelectedPhase()).getStatus().intValue() == Integer
                                .parseInt(ProjectStatusEnum.Extended.getStatusId())
                                && (d.getDeliverableInfo(this.getSelectedPhase()).getNewExpectedYear() != null
                                        && d.getDeliverableInfo(this.getSelectedPhase()).getNewExpectedYear()
                                                .intValue() == this.getSelectedYear()))
                        || (d.getDeliverableInfo(this.getSelectedPhase()).getStatus().intValue() == Integer
                                .parseInt(ProjectStatusEnum.Cancelled.getStatusId())
                                && (d.getDeliverableInfo(this.getSelectedPhase()).getYear() == this
                                        .getSelectedYear()
                                        || (d.getDeliverableInfo(this.getSelectedPhase())
                                                .getNewExpectedYear() != null
                                                && d.getDeliverableInfo(this.getSelectedPhase())
                                                        .getNewExpectedYear()
                                                        .intValue() == this.getSelectedYear()))))
                && (d.getDeliverableInfo(this.getSelectedPhase()).getStatus().intValue() == Integer
                        .parseInt(ProjectStatusEnum.Extended.getStatusId())
                        || d.getDeliverableInfo(this.getSelectedPhase()).getStatus().intValue() == Integer
                                .parseInt(ProjectStatusEnum.Complete.getStatusId())
                        || d.getDeliverableInfo(this.getSelectedPhase()).getStatus().intValue() == Integer
                                .parseInt(ProjectStatusEnum.Cancelled.getStatusId())))
                .collect(Collectors.toList());

        deliverables.sort((p1, p2) -> p1.getDeliverableInfo(this.getSelectedPhase())
                .isRequieriedReporting(this.getSelectedYear())
                .compareTo(p2.getDeliverableInfo(this.getSelectedPhase())
                        .isRequieriedReporting(this.getSelectedYear())));
        HashSet<Deliverable> deliverablesHL = new HashSet<>();
        deliverablesHL.addAll(deliverables);
        deliverables.clear();
        deliverables.addAll(deliverablesHL);
        for (Deliverable deliverable : deliverables) {
            String delivType = null, delivSubType = null, delivYear = null, keyOutput = "", leader = null,
                    institution = null, fundingSources = "", deliv_description = null;
            String delivStatus = deliverable.getDeliverableInfo(this.getSelectedPhase())
                    .getStatusName(this.getSelectedPhase());
            Boolean showFAIR = false, showPublication = false, showCompilance = false;

            if (deliverable.getDeliverableInfo().getDescription() != null
                    && !deliverable.getDeliverableInfo().getDescription().isEmpty()) {
                deliv_description = deliverable.getDeliverableInfo().getDescription();
            }

            if (deliverable.getDeliverableInfo().getDeliverableType() != null) {
                DeliverableType deliverableSubType = deliverable.getDeliverableInfo().getDeliverableType();
                delivSubType = deliverableSubType.getName();
                if (deliverableSubType.getFair() != null && deliverableSubType.getFair()) {
                    showFAIR = true;
                }
                showCompilance = this.hasDeliverableRule(deliverable.getDeliverableInfo(),
                        APConstants.DELIVERABLE_RULE_COMPILANCE_CHECK);
                showPublication = this.hasDeliverableRule(deliverable.getDeliverableInfo(),
                        APConstants.DELIVERABLE_RULE_PUBLICATION_METADATA);

                if (deliverableSubType.getDeliverableCategory() != null) {
                    DeliverableType deliverableType = deliverableSubType.getDeliverableCategory();
                    delivType = deliverableType.getName();
                    if (deliverableType.getFair() != null && deliverableType.getFair()) {
                        showFAIR = true;
                    }
                }
            }
            if (delivStatus.equals("")) {
                delivStatus = null;
            }
            if (deliverable.getDeliverableInfo().getYear() != 0) {
                delivYear = "" + deliverable.getDeliverableInfo().getYear();
            }
            if (deliverable.getDeliverableInfo().getCrpClusterKeyOutput() != null) {
                keyOutput += "? ";
                if (deliverable.getDeliverableInfo().getCrpClusterKeyOutput().getCrpClusterOfActivity()
                        .getCrpProgram() != null) {
                    keyOutput += deliverable.getDeliverableInfo().getCrpClusterKeyOutput()
                            .getCrpClusterOfActivity().getCrpProgram().getAcronym() + " - ";
                }
                keyOutput += deliverable.getDeliverableInfo().getCrpClusterKeyOutput().getKeyOutput();
            }
            // Get partner responsible and institution
            List<DeliverablePartnership> deliverablePartnershipResponsibles = deliverablePartnershipManager
                    .findByDeliverablePhaseAndType(deliverable.getId(), this.getSelectedPhase().getId(),
                            DeliverablePartnershipTypeEnum.RESPONSIBLE.getValue());
            if (deliverablePartnershipResponsibles != null && deliverablePartnershipResponsibles.size() > 0) {
                if (deliverablePartnershipResponsibles.size() > 1) {
                    LOG.warn("There are more than 1 deliverable responsibles for D" + deliverable.getId() + " "
                            + this.getSelectedPhase().toString());
                }
                DeliverablePartnership responisble = deliverablePartnershipResponsibles.get(0);

                if (responisble != null) {
                    if (responisble.getProjectPartnerPerson() != null) {
                        ProjectPartnerPerson responsibleppp = responisble.getProjectPartnerPerson();
                        leader = responsibleppp.getUser().getComposedName() + "<br>&lt;"
                                + responsibleppp.getUser().getEmail() + "&gt;";
                        if (responsibleppp.getProjectPartner() != null) {
                            if (responsibleppp.getProjectPartner().getInstitution() != null) {
                                institution = responsibleppp.getProjectPartner().getInstitution()
                                        .getComposedName();
                            }
                        }
                    }
                }
            }

            // Get funding sources if exist
            for (DeliverableFundingSource dfs : deliverable.getDeliverableFundingSources().stream()
                    .filter(d -> d.isActive() && d.getPhase() != null
                            && d.getPhase().equals(this.getSelectedPhase())
                            && d.getFundingSource().getFundingSourceInfo(this.getSelectedPhase()) != null)
                    .collect(Collectors.toList())) {
                fundingSources += "? " + dfs.getFundingSource().getComposedName() + "<br>";
            }
            if (fundingSources.isEmpty()) {
                fundingSources = null;
            }
            // Get cross_cutting dimension
            String crossCutting = "";
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingNa() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingNa() == true) {
                    crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? N/A <br>";
                }
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingGender() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingGender() == true) {
                    Long scoring = deliverable.getDeliverableInfo().getCrossCuttingScoreGender();
                    if (scoring != null) {
                        CrossCuttingScoring crossCuttingScoring = crossCuttingScoringManager
                                .getCrossCuttingScoringById(scoring);
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Gender ("
                                + crossCuttingScoring.getDescription() + ")<br>";
                    } else {
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Gender <br>";
                    }
                }
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingYouth() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingYouth() == true) {
                    Long scoring = deliverable.getDeliverableInfo().getCrossCuttingScoreYouth();
                    if (scoring != null) {
                        CrossCuttingScoring crossCuttingScoring = crossCuttingScoringManager
                                .getCrossCuttingScoringById(scoring);
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Youth ("
                                + crossCuttingScoring.getDescription() + ")<br>";
                    } else {
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Youth <br>";
                    }
                }
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingCapacity() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingCapacity() == true) {
                    Long scoring = deliverable.getDeliverableInfo().getCrossCuttingScoreCapacity();
                    if (scoring != null) {
                        CrossCuttingScoring crossCuttingScoring = crossCuttingScoringManager
                                .getCrossCuttingScoringById(scoring);
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Capacity Development ("
                                + crossCuttingScoring.getDescription() + ")<br>";
                    } else {
                        crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? Capacity Development <br>";
                    }
                }
            }
            if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingGender() != null) {
                if (deliverable.getDeliverableInfo(this.getSelectedPhase()).getCrossCuttingGender() == true) {
                    if (deliverable.getDeliverableGenderLevels() == null
                            || deliverable.getDeliverableGenderLevels().isEmpty()) {
                        crossCutting += "<br><b>Gender level(s):</b><br>&nbsp;&nbsp;&nbsp;&nbsp;&lt;Not Defined&gt;";
                    } else {
                        crossCutting += "<br><b>Gender level(s): </b><br>";
                        for (DeliverableGenderLevel dgl : deliverable.getDeliverableGenderLevels().stream()
                                .filter(dgl -> dgl.isActive() && dgl.getPhase() != null
                                        && dgl.getPhase().equals(this.getSelectedPhase()))
                                .collect(Collectors.toList())) {
                            if (dgl.getGenderLevel() != 0.0) {
                                crossCutting += "&nbsp;&nbsp;&nbsp;&nbsp;? " + genderTypeManager
                                        .getGenderTypeById(dgl.getGenderLevel()).getDescription() + "<br>";
                            }
                        }
                    }
                }
            }
            if (crossCutting.isEmpty()) {
                crossCutting = null;
            }
            if (keyOutput.isEmpty()) {
                keyOutput = null;
            }
            // Reporting
            Integer delivNewYear = null;
            String delivNewYearJustification = null;
            if (deliverable.getDeliverableInfo().getStatus() != null) {
                // Extended
                if (deliverable.getDeliverableInfo().getStatus().intValue() == Integer
                        .parseInt(ProjectStatusEnum.Extended.getStatusId())) {
                    if (deliverable.getDeliverableInfo().getNewExpectedYear() != null
                            && deliverable.getDeliverableInfo().getNewExpectedYear().intValue() != -1) {
                        delivNewYear = deliverable.getDeliverableInfo().getNewExpectedYear();
                    }
                    delivNewYearJustification = deliverable.getDeliverableInfo().getStatusDescription();
                }
                // Cancelled
                if (deliverable.getDeliverableInfo().getStatus().intValue() == Integer
                        .parseInt(ProjectStatusEnum.Cancelled.getStatusId())) {
                    delivNewYearJustification = deliverable.getDeliverableInfo().getStatusDescription();
                }
            }
            String delivDisseminationChannel = null;
            String delivDisseminationUrl = null;
            String delivOpenAccess = null;
            String delivLicense = null;
            String delivLicenseModifications = null;
            Boolean isDisseminated = false;
            String disseminated = "No";
            String restrictedAccess = null;
            String restrictedDate = null;
            Boolean isRestricted = false;
            Boolean isLastTwoRestricted = false;
            Boolean showDelivLicenseModifications = false;
            if (deliverable.getDeliverableDisseminations().stream().collect(Collectors.toList()).size() > 0
                    && deliverable.getDeliverableDisseminations().stream().collect(Collectors.toList())
                            .get(0) != null) {
                // Get deliverable dissemination
                DeliverableDissemination deliverableDissemination = deliverable.getDeliverableDisseminations()
                        .stream().collect(Collectors.toList()).get(0);
                if (deliverableDissemination.getAlreadyDisseminated() != null
                        && deliverableDissemination.getAlreadyDisseminated() == true) {
                    isDisseminated = true;
                    disseminated = "Yes";
                }
                if (deliverableDissemination.getDisseminationChannel() != null
                        && !deliverableDissemination.getDisseminationChannel().isEmpty()) {
                    RepositoryChannel repositoryChannel = repositoryChannelManager
                            .getRepositoryChannelByShortName(
                                    deliverableDissemination.getDisseminationChannel());
                    if (repositoryChannel != null) {
                        delivDisseminationChannel = repositoryChannel.getName();
                    }
                }
                if (deliverableDissemination.getDisseminationUrl() != null
                        && !deliverableDissemination.getDisseminationUrl().isEmpty()) {
                    delivDisseminationUrl = deliverableDissemination.getDisseminationUrl().replace(" ", "%20");
                }
                if (deliverableDissemination.getIsOpenAccess() != null) {
                    if (deliverableDissemination.getIsOpenAccess() == true) {
                        delivOpenAccess = "Yes";
                    } else {
                        // get the open access
                        delivOpenAccess = "No";
                        isRestricted = true;
                        if (deliverableDissemination.getIntellectualProperty() != null
                                && deliverableDissemination.getIntellectualProperty() == true) {
                            restrictedAccess = "Intellectual Property Rights (confidential information)";
                        }
                        if (deliverableDissemination.getLimitedExclusivity() != null
                                && deliverableDissemination.getLimitedExclusivity() == true) {
                            restrictedAccess = "Limited Exclusivity Agreements";
                        }
                        if (deliverableDissemination.getNotDisseminated() != null
                                && deliverableDissemination.getNotDisseminated() == true) {
                            restrictedAccess = "Not Disseminated";
                        }
                        if (deliverableDissemination.getRestrictedUseAgreement() != null
                                && deliverableDissemination.getRestrictedUseAgreement() == true) {
                            restrictedAccess = "Restricted Use AgreementOCS - Restricted access (if so, what are these periods?)";
                            isLastTwoRestricted = true;
                            if (deliverableDissemination.getRestrictedAccessUntil() != null) {
                                restrictedDate = "<b>Restricted access until: </b>"
                                        + deliverableDissemination.getRestrictedAccessUntil();
                            } else {
                                restrictedDate = "<b>Restricted access until: </b>&lt;Not Defined&gt;";
                            }
                        }
                        if (deliverableDissemination.getEffectiveDateRestriction() != null
                                && deliverableDissemination.getEffectiveDateRestriction() == true) {
                            restrictedAccess = "Effective Date Restriction - embargoed periods (if so, what are these periods?)";
                            isLastTwoRestricted = true;
                            if (deliverableDissemination.getRestrictedEmbargoed() != null) {
                                restrictedDate = "<b>Restricted embargoed date: </b>"
                                        + deliverableDissemination.getRestrictedEmbargoed();
                            } else {
                                restrictedDate = "<b>Restricted embargoed date: </b>&lt;Not Defined&gt;";
                            }
                        }
                    }
                }
                if (deliverable.getDeliverableInfo().getAdoptedLicense() != null) {
                    if (deliverable.getDeliverableInfo().getAdoptedLicense() == true) {
                        delivLicense = deliverable.getDeliverableInfo().getLicense();
                        if (delivLicense.equals("OTHER")) {
                            delivLicense = deliverable.getDeliverableInfo().getOtherLicense();
                            showDelivLicenseModifications = true;
                            if (deliverable.getDeliverableInfo().getAllowModifications() != null
                                    && deliverable.getDeliverableInfo().getAllowModifications() == true) {
                                delivLicenseModifications = "Yes";
                            } else {
                                delivLicenseModifications = "No";
                            }
                        }
                    } else {
                        delivLicense = "No";
                    }
                }
            }
            if (delivLicense != null && delivLicense.isEmpty()) {
                delivLicense = null;
            }

            // Intellectual Assets
            Boolean hasIntellectualAsset = false, isPantent = false, isPvp = false;
            String hasIntellectualAssetText = null, intellectualAssetApplicants = null,
                    intellectualAssetType = null, intellectualAssetTitle = null,
                    intellectualAssetFillingType = null, intellectualAssetPantentStatus = null,
                    intellectualAssetPatentType = null, intellectualAssetPvpVarietyName = null,
                    intellectualAssetPvpStatus = null, intellectualAssetPvpCountry = null,
                    intellectualAssetPvpApplicationNumber = null, intellectualAssetPvpBreederCrop = null,
                    intellectualAssetDateFilling = null, intellectualAssetDateRegistration = null,
                    intellectualAssetDateExpiry = null, intellectualAssetAdditionalInformation = null,
                    intellectualAssetLinkPublished = null, intellectualAssetCommunication = null;

            List<DeliverableIntellectualAsset> intellectualAssets = deliverable
                    .getDeliverableIntellectualAssets().stream()
                    .filter(c -> c.isActive() && c.getPhase().equals(this.getActualPhase()))
                    .collect(Collectors.toList());

            if (intellectualAssets != null && intellectualAssets.size() > 0) {
                DeliverableIntellectualAsset asset = intellectualAssets.get(0);
                if (asset.getHasPatentPvp() != null) {
                    hasIntellectualAsset = asset.getHasPatentPvp();
                    if (asset.getHasPatentPvp()) {
                        hasIntellectualAssetText = "Yes";
                        if (asset.getApplicant() != null && !asset.getApplicant().isEmpty()) {
                            intellectualAssetApplicants = asset.getApplicant();
                        }
                        if (asset.getType() != null && asset.getType().intValue() != -1) {
                            intellectualAssetType = DeliverableIntellectualAssetTypeEnum
                                    .getValue(asset.getType()).getType();

                            if (DeliverableIntellectualAssetTypeEnum.getValue(asset.getType())
                                    .equals(DeliverableIntellectualAssetTypeEnum.Patent)) {
                                // Patent
                                isPantent = true;
                                if (asset.getFillingType() != null && asset.getFillingType().getId() != -1) {
                                    intellectualAssetFillingType = asset.getFillingType().getName();
                                }
                                if (asset.getPatentStatus() != null && asset.getPatentStatus().getId() != -1) {
                                    intellectualAssetPantentStatus = asset.getPatentStatus().getName();
                                }
                                if (asset.getPatentType() != null && asset.getPatentType().intValue() != -1) {
                                    intellectualAssetPatentType = DeliverableIntellectualAssetPantentTypeEnum
                                            .getValue(asset.getPatentType()).getType();
                                }
                            } else if (DeliverableIntellectualAssetTypeEnum.getValue(asset.getType())
                                    .equals(DeliverableIntellectualAssetTypeEnum.PVP)) {
                                // PVP
                                isPvp = true;
                                if (asset.getVarietyName() != null && !asset.getVarietyName().isEmpty()) {
                                    intellectualAssetPvpVarietyName = asset.getVarietyName();
                                }

                                if (asset.getStatus() != null && asset.getStatus() != -1) {
                                    intellectualAssetPvpStatus = ProjectStatusEnum.getValue(asset.getStatus())
                                            .getStatus();
                                }
                                if (asset.getCountry() != null
                                        && !asset.getCountry().getIsoAlpha2().equals("-1")) {
                                    intellectualAssetPvpCountry = asset.getCountry().getName();
                                }
                                if (asset.getAppRegNumber() != null) {
                                    intellectualAssetPvpApplicationNumber = asset.getAppRegNumber() + "";
                                }
                                if (asset.getBreederCrop() != null && !asset.getBreederCrop().isEmpty()) {
                                    intellectualAssetPvpBreederCrop = intellectualAssetPvpVarietyName = asset
                                            .getBreederCrop();
                                }
                            }
                        }
                        if (asset.getTitle() != null && !asset.getTitle().isEmpty()) {
                            intellectualAssetTitle = asset.getTitle();
                        }
                        if (asset.getDateFilling() != null) {
                            intellectualAssetDateFilling = formatter.format(asset.getDateFilling());
                        }
                        if (asset.getDateRegistration() != null) {
                            intellectualAssetDateRegistration = formatter.format(asset.getDateRegistration());
                        }
                        if (asset.getDateExpiry() != null) {
                            intellectualAssetDateExpiry = formatter.format(asset.getDateExpiry());
                        }
                        if (asset.getAdditionalInformation() != null
                                && !asset.getAdditionalInformation().isEmpty()) {
                            intellectualAssetAdditionalInformation = asset.getAdditionalInformation();
                        }
                        if (asset.getLink() != null && !asset.getLink().isEmpty()) {
                            intellectualAssetLinkPublished = asset.getLink();
                        }
                        if (asset.getPublicCommunication() != null
                                && !asset.getPublicCommunication().isEmpty()) {
                            intellectualAssetCommunication = asset.getPublicCommunication();
                        }

                    } else {
                        hasIntellectualAssetText = "No";
                    }
                }
            }

            // Participants
            Boolean hasParticipants = false, isAcademicDegree = false, isRegional = false, isNational = false;
            String hasParticipantsText = null, participantEvent = null, participantActivityType = null,
                    participantAcademicDegree = null, participantTotalParticipants = null,
                    participantFemales = null, participantType = null, participantGeographicScope = null,
                    participantRegional = null, participantCountries = null;

            List<DeliverableParticipant> deliverableParticipants = deliverable.getDeliverableParticipants()
                    .stream().filter(c -> c.isActive() && c.getPhase().equals(this.getActualPhase()))
                    .collect(Collectors.toList());

            if (deliverableParticipants != null && deliverableParticipants.size() > 0) {
                DeliverableParticipant participant = deliverableParticipants.get(0);
                if (participant.getHasParticipants() != null) {
                    hasParticipants = participant.getHasParticipants();
                    if (participant.getHasParticipants()) {
                        hasParticipantsText = "Yes";
                        if (participant.getEventActivityName() != null
                                && !participant.getEventActivityName().isEmpty()) {
                            participantEvent = participant.getEventActivityName();
                        }

                        if (participant.getRepIndTypeActivity() != null
                                && participant.getRepIndTypeActivity().getId() != -1) {
                            participantActivityType = participant.getRepIndTypeActivity().getName();
                            if (participant.getRepIndTypeActivity().getId()
                                    .equals(this.getReportingIndTypeActivityAcademicDegree())) {
                                isAcademicDegree = true;
                                participantAcademicDegree = participant.getAcademicDegree();
                            }
                        }
                        if (participant.getParticipants() != null) {
                            participantTotalParticipants = participant.getParticipants() + "";
                        }
                        if (participant.getFemales() != null) {
                            participantFemales = participant.getFemales() + "";
                        }
                        if (participant.getRepIndTypeParticipant() != null
                                && participant.getRepIndTypeParticipant().getId() != -1) {
                            participantType = participant.getRepIndTypeParticipant().getName();
                        }
                        if (participant.getRepIndGeographicScope() != null
                                && participant.getRepIndGeographicScope().getId() != -1) {
                            participantGeographicScope = participant.getRepIndGeographicScope().getName();
                            // Regional
                            if (participant.getRepIndGeographicScope().getId()
                                    .equals(this.getReportingIndGeographicScopeRegional())) {
                                isRegional = true;
                                if (participant.getRepIndRegion() != null
                                        && participant.getRepIndRegion().getId() != -1) {
                                    participantRegional = participant.getRepIndRegion().getName();
                                }
                            }
                            // National/Sub-national/Multinational
                            if (!participant.getRepIndGeographicScope().getId()
                                    .equals(this.getReportingIndGeographicScopeGlobal())
                                    && !participant.getRepIndGeographicScope().getId()
                                            .equals(this.getReportingIndGeographicScopeRegional())) {
                                isNational = true;
                                List<DeliverableParticipantLocation> locations = participant
                                        .getDeliverableParticipantLocations().stream()
                                        .filter(pl -> pl.isActive()).collect(Collectors.toList());
                                if (locations != null && locations.size() > 0) {
                                    locations.sort((pl1, pl2) -> pl1.getLocElement().getName()
                                            .compareTo(pl2.getLocElement().getName()));
                                    Set<String> countries = new HashSet<String>();
                                    for (DeliverableParticipantLocation participantLocation : locations) {
                                        countries.add(participantLocation.getLocElement().getName());
                                    }
                                    participantCountries = String.join(", ", countries);
                                }
                            }
                        }

                    } else {
                        hasParticipantsText = "No";
                    }
                }
            }

            // Metadata

            String titleMetadata = null;
            String descriptionMetadata = null;
            String dateMetadata = null;
            String languageMetadata = null;
            String countryMetadata = null;
            String keywordsMetadata = null;
            String citationMetadata = null;
            String HandleMetadata = null;
            String DOIMetadata = null;
            for (DeliverableMetadataElement deliverableMetadataElement : deliverable
                    .getDeliverableMetadataElements().stream()
                    .filter(dm -> dm.isActive() && dm.getMetadataElement() != null)
                    .collect(Collectors.toList())) {
                if (deliverableMetadataElement.getMetadataElement().getId() == 1) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        titleMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
                if (deliverableMetadataElement.getMetadataElement().getId() == 8) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        descriptionMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
                if (deliverableMetadataElement.getMetadataElement().getId() == 17) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        dateMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
                if (deliverableMetadataElement.getMetadataElement().getId() == 24) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        languageMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
                if (deliverableMetadataElement.getMetadataElement().getId() == 28) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        countryMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
                if (deliverableMetadataElement.getMetadataElement().getId() == 37) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        keywordsMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
                if (deliverableMetadataElement.getMetadataElement().getId() == 22) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        citationMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
                if (deliverableMetadataElement.getMetadataElement().getId() == 35) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        HandleMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
                if (deliverableMetadataElement.getMetadataElement().getId() == 36) {
                    if (deliverableMetadataElement.getElementValue() != null
                            && !deliverableMetadataElement.getElementValue().isEmpty()) {
                        DOIMetadata = deliverableMetadataElement.getElementValue();
                    }
                }
            }
            String creatorAuthors = "";
            for (DeliverableUser deliverableUser : deliverable.getDeliverableUsers().stream()
                    .filter(du -> du.isActive()).collect(Collectors.toList())) {
                creatorAuthors += "<br>? ";
                if (!deliverableUser.getLastName().isEmpty()) {
                    creatorAuthors += deliverableUser.getLastName() + " - ";
                }
                if (!deliverableUser.getFirstName().isEmpty()) {
                    creatorAuthors += deliverableUser.getFirstName();
                }
                if (!deliverableUser.getElementId().isEmpty()) {
                    creatorAuthors += "&lt;" + deliverableUser.getElementId() + "&gt;";
                }
            }
            if (creatorAuthors.isEmpty()) {
                creatorAuthors = null;
            }
            String dataSharing = "";
            for (DeliverableDataSharingFile deliverableDataSharingFile : deliverable
                    .getDeliverableDataSharingFiles().stream().filter(ds -> ds.isActive())
                    .collect(Collectors.toList())) {
                if (deliverableDataSharingFile.getExternalFile() != null
                        && !deliverableDataSharingFile.getExternalFile().isEmpty()) {
                    dataSharing += deliverableDataSharingFile.getExternalFile().replace(" ", "%20") + "<br>";
                }
                if (deliverableDataSharingFile.getFile() != null
                        && deliverableDataSharingFile.getFile().isActive()) {
                    dataSharing += (this.getDeliverableDataSharingFilePath()
                            + deliverableDataSharingFile.getFile().getFileName()).replace(" ", "%20") + "<br>";
                }
            }
            if (dataSharing.isEmpty()) {
                dataSharing = null;
            }
            String qualityAssurance = "";
            String dataDictionary = "";
            String tools = "";
            if (deliverable.getDeliverableQualityChecks().stream().filter(qc -> qc.isActive())
                    .collect(Collectors.toList()).size() > 0
                    && deliverable.getDeliverableQualityChecks().stream().filter(qc -> qc.isActive())
                            .collect(Collectors.toList()).get(0) != null) {
                DeliverableQualityCheck deliverableQualityCheck = deliverable.getDeliverableQualityChecks()
                        .stream().filter(qc -> qc.isActive()).collect(Collectors.toList()).get(0);
                // QualityAssurance
                if (deliverableQualityCheck.getQualityAssurance() != null) {
                    if (deliverableQualityCheck.getQualityAssurance().getId() == 2) {
                        if (deliverableQualityCheck.getFileAssurance() != null
                                && deliverableQualityCheck.getFileAssurance().isActive()) {
                            qualityAssurance += "<br>? File: <font size=2 face='Segoe UI' color='blue'>"
                                    + (this.getDeliverableUrl("Assurance", deliverable)
                                            + deliverableQualityCheck.getFileAssurance().getFileName())
                                                    .replace(" ", "%20")
                                    + "</font>";
                        }
                        if (deliverableQualityCheck.getLinkAssurance() != null
                                && !deliverableQualityCheck.getLinkAssurance().isEmpty()) {
                            qualityAssurance += "<br>? Link: <font size=2 face='Segoe UI' color='blue'>"
                                    + deliverableQualityCheck.getLinkAssurance().replace(" ", "%20")
                                    + "</font>";
                        }
                    } else {
                        qualityAssurance = "? " + deliverableQualityCheck.getQualityAssurance().getName();
                    }
                }
                // Data dictionary
                if (deliverableQualityCheck.getDataDictionary() != null) {
                    if (deliverableQualityCheck.getDataDictionary().getId() == 2) {
                        if (deliverableQualityCheck.getFileDictionary() != null
                                && deliverableQualityCheck.getFileDictionary().isActive()) {
                            dataDictionary += "<br>? File: <font size=2 face='Segoe UI' color='blue'>"
                                    + (this.getDeliverableUrl("Dictionary", deliverable)
                                            + deliverableQualityCheck.getFileDictionary().getFileName())
                                                    .replace(" ", "%20")
                                    + "</font>";
                        }
                        if (deliverableQualityCheck.getLinkDictionary() != null
                                && !deliverableQualityCheck.getLinkDictionary().isEmpty()) {
                            dataDictionary += "<br>? Link: <font size=2 face='Segoe UI' color='blue'>"
                                    + deliverableQualityCheck.getLinkDictionary().replace(" ", "%20")
                                    + "</font>";
                        }
                    } else {
                        dataDictionary = "? " + deliverableQualityCheck.getDataDictionary().getName();
                    }
                }
                // Tools
                if (deliverableQualityCheck.getDataTools() != null) {
                    if (deliverableQualityCheck.getDataTools().getId() == 2) {
                        if (deliverableQualityCheck.getFileTools() != null
                                && deliverableQualityCheck.getFileTools().isActive()) {
                            tools += "<br>? File: <font size=2 face='Segoe UI' color='blue'>"
                                    + (this.getDeliverableUrl("Tools", deliverable)
                                            + deliverableQualityCheck.getFileTools().getFileName()).replace(" ",
                                                    "%20")
                                    + "</font>";
                        }
                        if (deliverableQualityCheck.getLinkTools() != null
                                && !deliverableQualityCheck.getLinkTools().isEmpty()) {
                            tools += "<br>? Link: <font size=2 face='Segoe UI' color='blue'>"
                                    + deliverableQualityCheck.getLinkTools().replace(" ", "%20") + "</font>";
                        }
                    } else {
                        tools = "? " + deliverableQualityCheck.getDataTools().getName();
                    }
                }
            }
            if (qualityAssurance.isEmpty()) {
                qualityAssurance = null;
            }
            if (dataDictionary.isEmpty()) {
                dataDictionary = null;
            }
            if (tools.isEmpty()) {
                tools = null;
            }
            // FAIR
            String F = "";
            if (this.isF(deliverable.getId()) == null) {
                F = "#cccccc";
            } else {
                if (this.isF(deliverable.getId()) == true) {
                    F = "#8ea786";
                } else {
                    F = "#D32F2F";
                }
            }
            String A = "";
            if (this.isA(deliverable.getId()) == null) {
                A += "#cccccc";
            } else {
                if (this.isA(deliverable.getId()) == true) {
                    A += "#8ea786";
                } else {
                    A += "#D32F2F";
                }
            }
            String I = "";
            if (this.isI(deliverable.getId()) == null) {
                I += "#cccccc";
            } else {
                if (this.isI(deliverable.getId()) == true) {
                    I += "#8ea786";
                } else {
                    I += "#D32F2F";
                }
            }
            String R = "";
            if (this.isR(deliverable.getId()) == null) {
                R += "#cccccc";
            } else {
                if (this.isR(deliverable.getId()) == true) {
                    R += "#8ea786";
                } else {
                    R += "#D32F2F";
                }
            }
            String volume = null;
            String issue = null;
            String pages = null;
            String journal = null;
            String journalIndicators = "";
            String acknowledge = null;
            String flContrib = "";
            // Publication metadata
            // Verify if the deliverable is of type Articles and Books
            if (deliverable.getDeliverablePublicationMetadatas().stream().filter(dpm -> dpm.isActive())
                    .collect(Collectors.toList()).size() > 0
                    && deliverable.getDeliverablePublicationMetadatas().stream().filter(dpm -> dpm.isActive())
                            .collect(Collectors.toList()).get(0) != null) {
                DeliverablePublicationMetadata deliverablePublicationMetadata = deliverable
                        .getDeliverablePublicationMetadatas().stream().filter(dpm -> dpm.isActive())
                        .collect(Collectors.toList()).get(0);
                volume = deliverablePublicationMetadata.getVolume();
                issue = deliverablePublicationMetadata.getIssue();
                pages = deliverablePublicationMetadata.getPages();
                journal = deliverablePublicationMetadata.getJournal();
                if (deliverablePublicationMetadata.getIsiPublication() != null
                        && deliverablePublicationMetadata.getIsiPublication() == true) {
                    journalIndicators += "? This journal article is an ISI publication <br>";
                }
                if (deliverablePublicationMetadata.getNasr() != null
                        && deliverablePublicationMetadata.getNasr() == true) {
                    journalIndicators += "? This article have a co-author from a developing country National Agricultural Research System (NARS)<br>";
                }
                if (deliverablePublicationMetadata.getCoAuthor() != null
                        && deliverablePublicationMetadata.getCoAuthor() == true) {
                    journalIndicators += "? This article have a co-author based in an Earth System Science-related academic department";
                }
                if (journalIndicators.isEmpty()) {
                    journalIndicators = null;
                }
                if (deliverablePublicationMetadata.getPublicationAcknowledge() != null
                        && deliverablePublicationMetadata.getPublicationAcknowledge() == true) {
                    acknowledge = "Yes";
                } else {
                    acknowledge = "No";
                }

                List<DeliverableCrp> deliverableCrps = deliverable.getDeliverableCrps().stream()
                        .filter(dc -> dc.isActive() && dc.getPhase() != null
                                && dc.getPhase().equals(this.getSelectedPhase()) && dc.getGlobalUnit() != null)
                        .collect(Collectors.toList());
                List<DeliverableCrp> deliverableFlagships = deliverable.getDeliverableCrps().stream()
                        .filter(dc -> dc.isActive() && dc.getPhase() != null
                                && dc.getPhase().equals(this.getSelectedPhase()) && dc.getCrpProgram() != null)
                        .collect(Collectors.toList());
                // Crps
                for (DeliverableCrp deliverableCrp : deliverableCrps) {
                    if (deliverableCrp.getGlobalUnit() != null) {
                        flContrib += "<br> ? " + deliverableCrp.getGlobalUnit().getComposedName();
                    }
                }
                // Flagships
                for (DeliverableCrp deliverableFlagship : deliverableFlagships) {
                    if (deliverableFlagship.getCrpProgram() != null) {
                        flContrib += "<br> ? " + deliverableFlagship.getCrpProgram().getComposedName();
                    }
                }

            }
            model.addRow(new Object[] { deliverable.getId(), deliverable.getDeliverableInfo().getTitle(),
                    delivType, delivSubType, delivStatus, delivYear, keyOutput, leader, institution,
                    fundingSources, crossCutting, delivNewYear, delivNewYearJustification,
                    delivDisseminationChannel, delivDisseminationUrl, delivOpenAccess, delivLicense,
                    titleMetadata, descriptionMetadata, dateMetadata, languageMetadata, countryMetadata,
                    keywordsMetadata, citationMetadata, HandleMetadata, DOIMetadata, creatorAuthors,
                    dataSharing, qualityAssurance, dataDictionary, tools, showFAIR, F, A, I, R, isDisseminated,
                    disseminated, restrictedAccess, isRestricted, restrictedDate, isLastTwoRestricted,
                    delivLicenseModifications, showDelivLicenseModifications, volume, issue, pages, journal,
                    journalIndicators, acknowledge, flContrib, showPublication, showCompilance,
                    deliv_description, hasIntellectualAsset, isPantent, isPvp, hasParticipants,
                    isAcademicDegree, isRegional, isNational, hasParticipantsText, participantEvent,
                    participantActivityType, participantAcademicDegree, participantTotalParticipants,
                    participantFemales, participantType, participantGeographicScope, participantRegional,
                    participantCountries, hasIntellectualAssetText, intellectualAssetApplicants,
                    intellectualAssetType, intellectualAssetTitle, intellectualAssetFillingType,
                    intellectualAssetPantentStatus, intellectualAssetPatentType,
                    intellectualAssetPvpVarietyName, intellectualAssetPvpStatus, intellectualAssetPvpCountry,
                    intellectualAssetPvpApplicationNumber, intellectualAssetPvpBreederCrop,
                    intellectualAssetDateFilling, intellectualAssetDateRegistration,
                    intellectualAssetDateExpiry, intellectualAssetAdditionalInformation,
                    intellectualAssetLinkPublished, intellectualAssetCommunication });
        }
    }
    return model;
}

From source file:ca.uhn.fhir.jpa.dao.SearchBuilder.java

/**
 * THIS SHOULD RETURN HASHSET and not jsut Set because we add to it later (so it can't be Collections.emptySet())
 * /*from w w w .  ja  va2s .  c om*/
 * @param theLastUpdated
 */
public static HashSet<Long> loadReverseIncludes(FhirContext theContext, EntityManager theEntityManager,
        Collection<Long> theMatches, Set<Include> theRevIncludes, boolean theReverseMode,
        DateRangeParam theLastUpdated) {
    if (theMatches.size() == 0) {
        return new HashSet<Long>();
    }
    if (theRevIncludes == null || theRevIncludes.isEmpty()) {
        return new HashSet<Long>();
    }
    String searchFieldName = theReverseMode ? "myTargetResourcePid" : "mySourceResourcePid";

    Collection<Long> nextRoundMatches = theMatches;
    HashSet<Long> allAdded = new HashSet<Long>();
    HashSet<Long> original = new HashSet<Long>(theMatches);
    ArrayList<Include> includes = new ArrayList<Include>(theRevIncludes);

    int roundCounts = 0;
    StopWatch w = new StopWatch();

    boolean addedSomeThisRound;
    do {
        roundCounts++;

        HashSet<Long> pidsToInclude = new HashSet<Long>();
        Set<Long> nextRoundOmit = new HashSet<Long>();

        for (Iterator<Include> iter = includes.iterator(); iter.hasNext();) {
            Include nextInclude = iter.next();
            if (nextInclude.isRecurse() == false) {
                iter.remove();
            }

            boolean matchAll = "*".equals(nextInclude.getValue());
            if (matchAll) {
                String sql;
                sql = "SELECT r FROM ResourceLink r WHERE r." + searchFieldName + " IN (:target_pids)";
                TypedQuery<ResourceLink> q = theEntityManager.createQuery(sql, ResourceLink.class);
                q.setParameter("target_pids", nextRoundMatches);
                List<ResourceLink> results = q.getResultList();
                for (ResourceLink resourceLink : results) {
                    if (theReverseMode) {
                        // if (theEverythingModeEnum.isEncounter()) {
                        // if (resourceLink.getSourcePath().equals("Encounter.subject") ||
                        // resourceLink.getSourcePath().equals("Encounter.patient")) {
                        // nextRoundOmit.add(resourceLink.getSourceResourcePid());
                        // }
                        // }
                        pidsToInclude.add(resourceLink.getSourceResourcePid());
                    } else {
                        pidsToInclude.add(resourceLink.getTargetResourcePid());
                    }
                }
            } else {

                List<String> paths;
                RuntimeSearchParam param = null;
                if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) {
                    paths = Collections.singletonList(nextInclude.getValue());
                } else {
                    String resType = nextInclude.getParamType();
                    if (isBlank(resType)) {
                        continue;
                    }
                    RuntimeResourceDefinition def = theContext.getResourceDefinition(resType);
                    if (def == null) {
                        ourLog.warn("Unknown resource type in include/revinclude=" + nextInclude.getValue());
                        continue;
                    }

                    String paramName = nextInclude.getParamName();
                    param = isNotBlank(paramName) ? def.getSearchParam(paramName) : null;
                    if (param == null) {
                        ourLog.warn("Unknown param name in include/revinclude=" + nextInclude.getValue());
                        continue;
                    }

                    paths = param.getPathsSplit();
                }

                String targetResourceType = defaultString(nextInclude.getParamTargetType(), null);
                for (String nextPath : paths) {
                    String sql;
                    boolean haveTargetTypesDefinedByParam = param != null && param.getTargets() != null
                            && param.getTargets().isEmpty() == false;
                    if (targetResourceType != null) {
                        sql = "SELECT r FROM ResourceLink r WHERE r.mySourcePath = :src_path AND r."
                                + searchFieldName
                                + " IN (:target_pids) AND r.myTargetResourceType = :target_resource_type";
                    } else if (haveTargetTypesDefinedByParam) {
                        sql = "SELECT r FROM ResourceLink r WHERE r.mySourcePath = :src_path AND r."
                                + searchFieldName
                                + " IN (:target_pids) AND r.myTargetResourceType in (:target_resource_types)";
                    } else {
                        sql = "SELECT r FROM ResourceLink r WHERE r.mySourcePath = :src_path AND r."
                                + searchFieldName + " IN (:target_pids)";
                    }
                    TypedQuery<ResourceLink> q = theEntityManager.createQuery(sql, ResourceLink.class);
                    q.setParameter("src_path", nextPath);
                    q.setParameter("target_pids", nextRoundMatches);
                    if (targetResourceType != null) {
                        q.setParameter("target_resource_type", targetResourceType);
                    } else if (haveTargetTypesDefinedByParam) {
                        q.setParameter("target_resource_types", param.getTargets());
                    }
                    List<ResourceLink> results = q.getResultList();
                    for (ResourceLink resourceLink : results) {
                        if (theReverseMode) {
                            Long pid = resourceLink.getSourceResourcePid();
                            pidsToInclude.add(pid);
                        } else {
                            Long pid = resourceLink.getTargetResourcePid();
                            pidsToInclude.add(pid);
                        }
                    }
                }
            }
        }

        if (theLastUpdated != null && (theLastUpdated.getLowerBoundAsInstant() != null
                || theLastUpdated.getUpperBoundAsInstant() != null)) {
            pidsToInclude = new HashSet<Long>(
                    filterResourceIdsByLastUpdated(theEntityManager, theLastUpdated, pidsToInclude));
        }
        for (Long next : pidsToInclude) {
            if (original.contains(next) == false && allAdded.contains(next) == false) {
                theMatches.add(next);
            }
        }

        pidsToInclude.removeAll(nextRoundOmit);

        addedSomeThisRound = allAdded.addAll(pidsToInclude);
        nextRoundMatches = pidsToInclude;
    } while (includes.size() > 0 && nextRoundMatches.size() > 0 && addedSomeThisRound);

    ourLog.info("Loaded {} {} in {} rounds and {} ms", new Object[] { allAdded.size(),
            theReverseMode ? "_revincludes" : "_includes", roundCounts, w.getMillisAndRestart() });

    return allAdded;
}

From source file:org.apache.hadoop.hive.ql.exec.tez.WorkloadManager.java

/**
 * This is the main method of the master thread the processes one set of events.
 * Be mindful of the fact that events can be queued while we are processing events, so
 * in addition to making sure we keep the current set consistent (e.g. no need to handle
 * update errors for a session that should already be destroyed), this needs to guard itself
 * against the future iterations - e.g. what happens if we kill a query due to plan change,
 * but the DAG finished before the kill happens and the user queues a "return" event? Etc.
 * DO NOT block for a long time in this method.
 * @param e Input events./* w  ww . j  a va 2  s  .  c  o  m*/
 * @param syncWork Output tasks that cannot be called via async methods.
 */
private void processCurrentEvents(EventState e, WmThreadSyncWork syncWork) throws Exception {
    // The order of processing is as follows. We'd reclaim or kill all the sessions that we can
    // reclaim from various user actions and errors, then apply the new plan if any,
    // then give out all we can give out (restart, get and reopen callers) and rebalance the
    // resource allocations in all the affected pools.
    // For every session, we'd check all the concurrent things happening to it.

    // TODO: also account for Tez-internal session restarts;
    //       AM reg info changes; add notifications, ignore errors, and update alloc.
    HashSet<String> poolsToRedistribute = new HashSet<>();

    // 0. Handle initialization results.
    for (SessionInitContext sw : e.initResults) {
        handleInitResultOnMasterThread(sw, syncWork, poolsToRedistribute);
    }
    e.initResults.clear();

    // 1. Handle kill query results - part 1, just put them in place. We will resolve what
    //    to do with the sessions after we go thru all the concurrent user actions.
    for (Map.Entry<WmTezSession, Boolean> entry : e.killQueryResults.entrySet()) {
        WmTezSession killQuerySession = entry.getKey();
        boolean killResult = entry.getValue();
        LOG.debug("Processing KillQuery {} for {}", killResult ? "success" : "failure", killQuerySession);
        // Note: do not cancel any user actions here; user actions actually interact with kills.
        KillQueryContext killCtx = killQueryInProgress.get(killQuerySession);
        if (killCtx == null) {
            LOG.error("Internal error - cannot find the context for killing {}", killQuerySession);
            continue;
        }
        killCtx.handleKillQueryCallback(!killResult);
    }
    e.killQueryResults.clear();

    // 2. Handle sessions that are being destroyed by users. Destroy implies return.
    for (WmTezSession sessionToDestroy : e.toDestroy) {
        if (e.toReturn.remove(sessionToDestroy)) {
            LOG.warn("The session was both destroyed and returned by the user; destroying");
        }
        LOG.info("Destroying {}", sessionToDestroy);
        RemoveSessionResult rr = handleReturnedInUseSessionOnMasterThread(e, sessionToDestroy,
                poolsToRedistribute, false);
        if (rr == RemoveSessionResult.OK || rr == RemoveSessionResult.NOT_FOUND) {
            // Restart even if there's an internal error.
            syncWork.toRestartInUse.add(sessionToDestroy);
        }
    }
    e.toDestroy.clear();

    // 3. Now handle actual returns. Sessions may be returned to the pool or may trigger expires.
    for (WmTezSession sessionToReturn : e.toReturn) {
        LOG.info("Returning {}", sessionToReturn);
        RemoveSessionResult rr = handleReturnedInUseSessionOnMasterThread(e, sessionToReturn,
                poolsToRedistribute, true);
        switch (rr) {
        case OK:
            WmEvent wmEvent = new WmEvent(WmEvent.EventType.RETURN);
            boolean wasReturned = tezAmPool.returnSessionAsync(sessionToReturn);
            if (!wasReturned) {
                syncWork.toDestroyNoRestart.add(sessionToReturn);
            } else {
                if (sessionToReturn.getWmContext() != null
                        && sessionToReturn.getWmContext().isQueryCompleted()) {
                    sessionToReturn.resolveReturnFuture();
                }
                wmEvent.endEvent(sessionToReturn);
            }
            break;
        case NOT_FOUND:
            syncWork.toRestartInUse.add(sessionToReturn); // Restart if there's an internal error.
            break;
        case IGNORE:
            break;
        default:
            throw new AssertionError("Unknown state " + rr);
        }
    }
    e.toReturn.clear();

    // 4. Reopen is essentially just destroy + get a new session for a session in use.
    for (Map.Entry<WmTezSession, SettableFuture<WmTezSession>> entry : e.toReopen.entrySet()) {
        LOG.info("Reopening {}", entry.getKey());
        handeReopenRequestOnMasterThread(e, entry.getKey(), entry.getValue(), poolsToRedistribute, syncWork);
    }
    e.toReopen.clear();

    // 5. All the sessions in use that were not destroyed or returned with a failed update now die.
    for (Map.Entry<WmTezSession, Integer> entry : e.updateErrors.entrySet()) {
        WmTezSession sessionWithUpdateError = entry.getKey();
        int failedEndpointVersion = entry.getValue();
        LOG.info("Update failed for {}", sessionWithUpdateError);
        handleUpdateErrorOnMasterThread(sessionWithUpdateError, failedEndpointVersion, e.toReuse, syncWork,
                poolsToRedistribute);
    }
    e.updateErrors.clear();

    // 6. Now apply a resource plan if any. This is expected to be pretty rare.
    boolean hasRequeues = false;
    if (e.resourcePlanToApply != null || e.doClearResourcePlan) {
        LOG.info("Applying new resource plan");
        int getReqCount = e.getRequests.size();
        applyNewResourcePlanOnMasterThread(e, syncWork, poolsToRedistribute);
        hasRequeues = getReqCount != e.getRequests.size();
    }
    e.resourcePlanToApply = null;
    e.doClearResourcePlan = false;

    // 7. Handle any move session requests. The way move session works right now is
    // a) sessions get moved to destination pool if there is capacity in destination pool
    // b) if there is no capacity in destination pool, the session gets killed (since we cannot pause a query)
    // TODO: in future this the process of killing can be delayed until the point where a session is actually required.
    // We could consider delaying the move (when destination capacity is full) until there is claim in src pool.
    // May be change command to support ... DELAYED MOVE TO etl ... which will run under src cluster fraction as long
    // as possible
    Map<WmTezSession, WmEvent> recordMoveEvents = new HashMap<>();
    for (MoveSession moveSession : e.moveSessions) {
        handleMoveSessionOnMasterThread(moveSession, syncWork, poolsToRedistribute, e.toReuse,
                recordMoveEvents);
    }
    e.moveSessions.clear();

    // 8. Handle all the get/reuse requests. We won't actually give out anything here, but merely
    //    map all the requests and place them in an appropriate order in pool queues. The only
    //    exception is the reuse without queue contention; can be granted immediately. If we can't
    //    reuse the session immediately, we will convert the reuse to a normal get, because we
    //    want query level fairness, and don't want the get in queue to hold up a session.
    GetRequest req;
    while ((req = e.getRequests.pollFirst()) != null) {
        LOG.info("Processing a new get request from " + req.mappingInput);
        queueGetRequestOnMasterThread(req, poolsToRedistribute, syncWork);
    }
    e.toReuse.clear();

    // 9. Resolve all the kill query requests in flight. Nothing below can affect them.
    Iterator<KillQueryContext> iter = killQueryInProgress.values().iterator();
    while (iter.hasNext()) {
        KillQueryContext ctx = iter.next();
        KillQueryResult kr = ctx.process();
        switch (kr) {
        case IN_PROGRESS:
            continue; // Either the user or the kill is not done yet.
        case OK: {
            iter.remove();
            LOG.debug("Kill query succeeded; returning to the pool: {}", ctx.session);
            ctx.killSessionFuture.set(true);
            WmEvent wmEvent = new WmEvent(WmEvent.EventType.RETURN);
            if (!tezAmPool.returnSessionAsync(ctx.session)) {
                syncWork.toDestroyNoRestart.add(ctx.session);
            } else {
                if (ctx.session.getWmContext() != null && ctx.session.getWmContext().isQueryCompleted()) {
                    ctx.session.resolveReturnFuture();
                }
                wmEvent.endEvent(ctx.session);
            }
            break;
        }
        case RESTART_REQUIRED: {
            iter.remove();
            ctx.killSessionFuture.set(true);
            LOG.debug("Kill query failed; restarting: {}", ctx.session);
            // Note: we assume here the session, before we resolve killQuery result here, is still
            //       "in use". That is because all the user ops above like return, reopen, etc.
            //       don't actually return/reopen/... when kill query is in progress.
            syncWork.toRestartInUse.add(ctx.session);
            break;
        }
        default:
            throw new AssertionError("Unknown state " + kr);
        }
    }

    // 10. If there was a cluster state change, make sure we redistribute all the pools.
    if (e.hasClusterStateChanged) {
        LOG.info("Processing a cluster state change");
        poolsToRedistribute.addAll(pools.keySet());
        e.hasClusterStateChanged = false;
    }

    // 11. Finally, for all the pools that have changes, promote queued queries and rebalance.
    for (String poolName : poolsToRedistribute) {
        if (LOG.isDebugEnabled()) {
            LOG.info("Processing changes for pool " + poolName + ": " + pools.get(poolName));
        }
        processPoolChangesOnMasterThread(poolName, hasRequeues, syncWork);
    }

    // 12. Save state for future iterations.
    for (KillQueryContext killCtx : syncWork.toKillQuery.values()) {
        if (killQueryInProgress.put(killCtx.session, killCtx) != null) {
            LOG.error("One query killed several times - internal error {}", killCtx.session);
        }
    }

    // 13. To record move events, we need to cluster fraction updates that happens at step 11.
    for (Map.Entry<WmTezSession, WmEvent> entry : recordMoveEvents.entrySet()) {
        entry.getValue().endEvent(entry.getKey());
    }

    // 14. Give our final state to UI/API requests if any.
    if (e.dumpStateFuture != null) {
        List<String> result = new ArrayList<>();
        result.add("RESOURCE PLAN " + rpName + "; default pool " + defaultPool);
        for (PoolState ps : pools.values()) {
            dumpPoolState(ps, result);
        }
        e.dumpStateFuture.set(result);
        e.dumpStateFuture = null;
    }

    // 15. Notify tests and global async ops.
    for (SettableFuture<Boolean> testEvent : e.testEvents) {
        LOG.info("Triggering test event " + System.identityHashCode(testEvent));
        testEvent.set(null);
    }
    e.testEvents.clear();

    if (e.applyRpFuture != null) {
        e.applyRpFuture.set(true);
        e.applyRpFuture = null;
    }
}

From source file:org.codehaus.enunciate.modules.rest.RESTOperation.java

/**
 * Construct a REST operation.//w  w  w . ja v a 2s . c  o  m
 *
 * @param resource The resource for this operation.
 * @param contentType The content type of the operation.
 * @param verb     The verb for the operation.
 * @param method   The method.
 * @param parameterNames The parameter names.
 */
protected RESTOperation(RESTResource resource, String contentType, VerbType verb, Method method,
        String[] parameterNames) {
    this.resource = resource;
    this.verb = verb;
    this.method = method;
    this.contentType = contentType;

    int properNounIndex = -1;
    Class properNoun = null;
    Boolean properNounOptional = null;
    int nounValueIndex = -1;
    Class nounValue = null;
    Boolean nounValueOptional = Boolean.FALSE;
    int contentTypeParameterIndex = -1;
    adjectiveTypes = new HashMap<String, Class>();
    adjectiveIndices = new HashMap<String, Integer>();
    adjectivesOptional = new HashMap<String, Boolean>();
    complexAdjectives = new ArrayList<String>();
    contextParameterTypes = new HashMap<String, Class>();
    contextParameterIndices = new HashMap<String, Integer>();
    Class[] parameterTypes = method.getParameterTypes();
    HashSet<Class> contextClasses = new HashSet<Class>();
    for (int i = 0; i < parameterTypes.length; i++) {
        Class parameterType = Collection.class.isAssignableFrom(parameterTypes[i])
                ? getCollectionTypeAsArrayType(method, i)
                : parameterTypes[i];

        boolean isAdjective = true;
        String adjectiveName = "arg" + i;
        if ((parameterNames != null) && (parameterNames.length > i) && (parameterNames[i] != null)) {
            adjectiveName = parameterNames[i];
        }
        boolean adjectiveOptional = !parameterType.isPrimitive();
        boolean adjectiveComplex = false;
        Annotation[] parameterAnnotations = method.getParameterAnnotations()[i];
        for (Annotation annotation : parameterAnnotations) {
            if (annotation instanceof ProperNoun) {
                if (parameterType.isArray()) {
                    throw new IllegalStateException(
                            "Proper nouns must be simple types, found an array or collection for parameter " + i
                                    + " of method " + method.getDeclaringClass().getName() + "."
                                    + method.getName() + ".");
                } else if (properNoun == null) {
                    ProperNoun properNounInfo = (ProperNoun) annotation;
                    if (properNounInfo.optional()) {
                        if (parameterType.isPrimitive()) {
                            throw new IllegalStateException(
                                    "An optional proper noun cannot be a primitive type for method "
                                            + method.getDeclaringClass().getName() + "." + method.getName()
                                            + ".");
                        }

                        properNounOptional = true;
                    }

                    if (!properNounInfo.converter().equals(ProperNoun.DEFAULT.class)) {
                        try {
                            ConvertUtils.register((Converter) properNounInfo.converter().newInstance(),
                                    parameterType);
                        } catch (ClassCastException e) {
                            throw new IllegalArgumentException("Illegal converter class for method "
                                    + method.getDeclaringClass().getName() + "." + method.getName()
                                    + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                        } catch (Exception e) {
                            throw new IllegalArgumentException("Unable to instantiate converter class "
                                    + properNounInfo.converter().getName() + " on method "
                                    + method.getDeclaringClass().getName() + "." + method.getName() + ".", e);
                        }
                    }

                    properNoun = parameterType;
                    properNounIndex = i;
                    isAdjective = false;
                    break;
                } else {
                    throw new IllegalStateException("There are two proper nouns for method "
                            + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }
            } else if (annotation instanceof NounValue) {
                if ((!parameterType.isAnnotationPresent(XmlRootElement.class))
                        && (!parameterType.equals(DataHandler.class)) && (!(parameterType.isArray()
                                && parameterType.getComponentType().equals(DataHandler.class)))) {
                    LOG.warn(
                            "Enunciate doesn't support unmarshalling objects of type " + parameterType.getName()
                                    + ". Unless a custom content type handler is provided, this operation ("
                                    + method.getDeclaringClass() + "." + method.getName() + ") will fail.");
                }

                if (nounValue == null) {
                    if (((NounValue) annotation).optional()) {
                        if (parameterType.isPrimitive()) {
                            throw new IllegalStateException(
                                    "An optional noun value cannot be a primitive type for method "
                                            + method.getDeclaringClass().getName() + "." + method.getName()
                                            + ".");
                        }

                        nounValueOptional = true;
                    }

                    nounValue = parameterType;
                    nounValueIndex = i;
                    isAdjective = false;
                    break;
                } else {
                    throw new IllegalStateException("There are two proper nouns for method "
                            + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }
            } else if (annotation instanceof ContextParameter) {
                ContextParameter contextParameterInfo = (ContextParameter) annotation;
                String contextParameterName = contextParameterInfo.value();

                if (!contextParameterInfo.converter().equals(ContextParameter.DEFAULT.class)) {
                    try {
                        ConvertUtils.register((Converter) contextParameterInfo.converter().newInstance(),
                                parameterType);
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException("Illegal converter class for method "
                                + method.getDeclaringClass().getName() + "." + method.getName()
                                + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                    } catch (Exception e) {
                        throw new IllegalArgumentException(
                                "Unable to instantiate converter class "
                                        + contextParameterInfo.converter().getName() + " on method "
                                        + method.getDeclaringClass().getName() + "." + method.getName() + ".",
                                e);
                    }
                }

                contextParameterTypes.put(contextParameterName, parameterType);
                contextParameterIndices.put(contextParameterName, i);
                isAdjective = false;
                break;
            } else if (annotation instanceof ContentTypeParameter) {
                contentTypeParameterIndex = i;
                isAdjective = false;
                break;
            } else if (annotation instanceof Adjective) {
                Adjective adjectiveInfo = (Adjective) annotation;
                adjectiveOptional = adjectiveInfo.optional();
                if (adjectiveOptional && parameterType.isPrimitive()) {
                    throw new IllegalStateException(
                            "An optional adjective cannot be a primitive type for method "
                                    + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }

                if (!"##default".equals(adjectiveInfo.name())) {
                    adjectiveName = adjectiveInfo.name();
                }

                adjectiveComplex = adjectiveInfo.complex();

                if (!adjectiveInfo.converter().equals(Adjective.DEFAULT.class)) {
                    try {
                        ConvertUtils.register((Converter) adjectiveInfo.converter().newInstance(),
                                parameterType);
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException("Illegal converter class for method "
                                + method.getDeclaringClass().getName() + "." + method.getName()
                                + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Unable to instantiate converter class "
                                + adjectiveInfo.converter().getName() + " on method "
                                + method.getDeclaringClass().getName() + "." + method.getName() + ".", e);
                    }
                }

                break;
            }
        }

        if (isAdjective) {
            this.adjectiveTypes.put(adjectiveName, parameterType);
            this.adjectiveIndices.put(adjectiveName, i);
            this.adjectivesOptional.put(adjectiveName, adjectiveOptional);
            if (adjectiveComplex) {
                this.complexAdjectives.add(adjectiveName);
            }
        }

        if (parameterType.isArray()) {
            contextClasses.add(parameterType.getComponentType());
        } else {
            contextClasses.add(parameterType);
        }
    }

    Class returnType = null;
    if (!Void.TYPE.equals(method.getReturnType())) {
        returnType = method.getReturnType();

        if (!returnType.isAnnotationPresent(XmlRootElement.class)
                && (!DataHandler.class.isAssignableFrom(returnType))) {
            LOG.warn("Enunciate doesn't support marshalling objects of type " + returnType.getName()
                    + ". Unless a custom content type handler is provided, this operation ("
                    + method.getDeclaringClass() + "." + method.getName() + ") will fail.");
        }

        contextClasses.add(returnType);
    }

    for (Class exceptionClass : method.getExceptionTypes()) {
        for (Method exceptionMethod : exceptionClass.getMethods()) {
            if ((exceptionMethod.isAnnotationPresent(RESTErrorBody.class))
                    && (exceptionMethod.getReturnType() != Void.TYPE)) {
                //add the error body to the context classes.
                contextClasses.add(exceptionMethod.getReturnType());
            }
        }
    }

    //now load any additional context classes as specified by @RESTSeeAlso
    if (method.isAnnotationPresent(RESTSeeAlso.class)) {
        contextClasses.addAll(Arrays.asList(method.getAnnotation(RESTSeeAlso.class).value()));
    }
    if (method.getDeclaringClass().isAnnotationPresent(RESTSeeAlso.class)) {
        contextClasses
                .addAll(Arrays.asList(method.getDeclaringClass().getAnnotation(RESTSeeAlso.class).value()));
    }
    if ((method.getDeclaringClass().getPackage() != null)
            && (method.getDeclaringClass().getPackage().isAnnotationPresent(RESTSeeAlso.class))) {
        contextClasses.addAll(Arrays
                .asList(method.getDeclaringClass().getPackage().getAnnotation(RESTSeeAlso.class).value()));
    }

    String jsonpParameter = null;
    JSONP jsonpInfo = method.getAnnotation(JSONP.class);
    if (jsonpInfo == null) {
        jsonpInfo = method.getDeclaringClass().getAnnotation(JSONP.class);
        if (jsonpInfo == null) {
            jsonpInfo = method.getDeclaringClass().getPackage().getAnnotation(JSONP.class);
        }
    }
    if (jsonpInfo != null) {
        jsonpParameter = jsonpInfo.paramName();
    }

    String charset = "utf-8";
    org.codehaus.enunciate.rest.annotations.ContentType contentTypeInfo = method
            .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
    if (contentTypeInfo == null) {
        contentTypeInfo = method.getDeclaringClass()
                .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
        if (contentTypeInfo == null) {
            contentTypeInfo = method.getDeclaringClass().getPackage()
                    .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
        }
    }
    if (contentTypeInfo != null) {
        charset = contentTypeInfo.charset();
    }

    String defaultNamespace = "";
    if (method.getDeclaringClass().getPackage() != null
            && method.getDeclaringClass().getPackage().isAnnotationPresent(XmlSchema.class)) {
        defaultNamespace = method.getDeclaringClass().getPackage().getAnnotation(XmlSchema.class).namespace();
    }

    this.properNounType = properNoun;
    this.properNounIndex = properNounIndex;
    this.properNounOptional = properNounOptional;
    this.nounValueType = nounValue;
    this.nounValueIndex = nounValueIndex;
    this.nounValueOptional = nounValueOptional;
    this.resultType = returnType;
    this.charset = charset;
    this.JSONPParameter = jsonpParameter;
    this.contextClasses = contextClasses;
    this.contentTypeParameterIndex = contentTypeParameterIndex;
    this.defaultNamespace = defaultNamespace;
}

From source file:lineage2.gameserver.model.Player.java

/**
 * Method restoreSkills./* w ww .j a  v  a  2s.c o m*/
 */
private void restoreSkills() {
    //----------------------------------------------
    List<Integer> keepskill = new ArrayList<Integer>();
    //Nobless Skills
    keepskill.add(325);
    //Common Craft Skills
    keepskill.add(1320);
    //Mentor Skills
    keepskill.add(9227);
    keepskill.add(9228);
    keepskill.add(9229);
    keepskill.add(9230);
    keepskill.add(9231);
    keepskill.add(9232);
    keepskill.add(9233);
    keepskill.add(9256);
    keepskill.add(9376);
    keepskill.add(9377);
    keepskill.add(9378);
    keepskill.add(9379);
    //------------------------------------------------
    Connection con = null;
    PreparedStatement statement = null;
    ResultSet rset = null;
    try {
        con = DatabaseFactory.getInstance().getConnection();
        statement = con.prepareStatement(
                "SELECT skill_id,skill_level FROM character_skills WHERE char_obj_id=? AND (class_index=? OR class_index=-1)");
        statement.setInt(1, getObjectId());
        statement.setInt(2, getActiveClassId());
        rset = statement.executeQuery();
        List<Integer> _relationSkillToRemove = new ArrayList<Integer>();
        List<Integer> _SkillToRemove = new ArrayList<Integer>();
        while (rset.next()) {
            final int id = rset.getInt("skill_id");
            final int level = rset.getInt("skill_level");
            final Skill skill = SkillTable.getInstance().getInfo(id, level);
            if (skill == null) {
                _log.warn("Problem! RestoreSkill Id: " + id + " level: " + level);
                continue;
            }
            if (!isAwaking() && !SkillAcquireHolder.getInstance().isSkillPossible(this, skill)) {
                if (!keepskill.contains(skill.getId())) {
                    _SkillToRemove.add(skill.getId());
                    //removeSkill(skill, true);
                    removeSkillFromShortCut(skill.getId());
                    _log.info("SkillTree: Removed skill: " + skill.getId() + " - " + skill.getName()
                            + " to the player " + getName());
                    continue;
                }
            }
            //-------------------
            //SKILL RACE CHECK
            //-------------------
            if (isAwaking() && !SkillAcquireHolder.getInstance().isSkillRacePossible(this, skill)) {
                _SkillToRemove.add(skill.getId());
                //removeSkill(skill, true);
                _log.info("Race Skill Removed: " + skill.getId() + " - " + skill.getName() + " to the player "
                        + getName());
                continue;
            }
            //-------------------
            //SKILL DB CHECK
            //-------------------
            if (!SkillAcquireHolder.getInstance().isSkillPossible(this, skill)) {
                if (!SkillAcquireHolder.getInstance().getAllClassSkillId().contains(skill.getId())) {
                    if (!keepskill.contains(skill.getId())) {
                        _SkillToRemove.add(skill.getId());
                        //removeSkill(skill, true);
                        _log.info("Removed Skill: " + skill.getId() + " - " + skill.getName()
                                + " to the player " + getName());
                        continue;
                    }
                }
            }
            //-------------------
            if (Config.ALT_DELETE_SKILL_RELATION && skill.isRelationSkill()) {
                int[] _ss = skill.getRelationSkills();
                for (int _k : _ss) {
                    _relationSkillToRemove.add(_k);
                }
            }
            super.addSkill(skill);
        }

        removeSkills(_SkillToRemove, true);

        if (isNoble()) {
            updateNobleSkills();
        }
        if (_hero && getSubClassList().isBaseClassActive()) {
            Hero.addSkills(this);
        }
        if (_clan != null) {
            _clan.addSkillsQuietly(this);
            if ((_clan.getLeaderId() == getObjectId()) && (_clan.getLevel() >= 5)) {
                SiegeUtils.addSiegeSkills(this);
            }
        }
        if (((getActiveClassId() >= 53) && (getActiveClassId() <= 57)) || (getActiveClassId() == 117)
                || (getActiveClassId() == 118)) {
            super.addSkill(SkillTable.getInstance().getInfo(1321, 1));
        }
        super.addSkill(SkillTable.getInstance().getInfo(1322, 1));
        if (Config.UNSTUCK_SKILL && (getSkillLevel(1050) < 0)) {
            super.addSkill(SkillTable.getInstance().getInfo(2099, 1));
        }
        if (Config.ALT_DELETE_SKILL_RELATION) {
            HashSet<Integer> _tmp = new HashSet<Integer>();
            _tmp.addAll(_relationSkillToRemove);
            _relationSkillToRemove.clear();
            _relationSkillToRemove.addAll(_tmp);
            for (Skill s : getAllSkills()) {
                if (_relationSkillToRemove.contains(s.getId())) {
                    removeSkill(s, true);
                    removeSkillFromShortCut(s.getId());
                    _log.info("SkillRelation: Removed skill: " + s.getId() + " - " + s.getName()
                            + " to the player " + getName());
                }
            }
        }
    } catch (final Exception e) {
        _log.warn("Could not restore skills for player objId: " + getObjectId());
        _log.error("", e);
    } finally {
        DbUtils.closeQuietly(con, statement, rset);
    }
}

From source file:org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.java

@Override
public HashSet<ReadEntity> getAllInputs() {
    HashSet<ReadEntity> readEntities = new HashSet<ReadEntity>(getInputs());
    for (CTEClause cte : rootClause.asExecutionOrder()) {
        if (cte.source != null) {
            readEntities.addAll(cte.source.getInputs());
        }//w  w  w  .j a va2 s  . co  m
    }
    return readEntities;
}

From source file:org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.java

@Override
public HashSet<WriteEntity> getAllOutputs() {
    HashSet<WriteEntity> writeEntities = new HashSet<WriteEntity>(getOutputs());
    for (CTEClause cte : rootClause.asExecutionOrder()) {
        if (cte.source != null) {
            writeEntities.addAll(cte.source.getOutputs());
        }/*www  . j  a  va 2 s  . c  o  m*/
    }
    return writeEntities;
}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

@Override
public <E> TableMetadata<E> resolve(final Class<E> entityType) {
    log.info("Resolving metadata for " + entityType.getCanonicalName());
    final String tableName;
    final String schema;
    final Set<Set<String>> uniqueColumns = new HashSet<Set<String>>();
    final Set<String> keyColumns = new HashSet<String>();
    final Set<String> foreignKeys = new HashSet<String>();
    final HashSet<RelationMetadata<E, ?>> foreignReferences = new HashSet<RelationMetadata<E, ?>>();
    if (entityType.isAnnotationPresent(Table.class)) {
        final Table table = entityType.getAnnotation(Table.class);
        tableName = table.name().isEmpty() ? entityType.getSimpleName() : table.name();
        schema = table.schema();/*from w ww .j  a v a 2  s  .  c o  m*/
        for (UniqueConstraint constraint : table.uniqueConstraints()) {
            final HashSet<String> columns = new HashSet<String>();
            uniqueColumns.add(columns);
            Collections.addAll(columns, constraint.columnNames());
        }
    } else {
        tableName = entityType.getSimpleName();
        schema = NO_SCHEMA;
    }
    final Set<StoredProcedureMetadata> storedProcedures = new HashSet<StoredProcedureMetadata>();
    if (entityType.isAnnotationPresent(StoredProcedure.class)) {
        storedProcedures.add(getStoredProcedureMetadata(entityType.getAnnotation(StoredProcedure.class)));
    } else if (entityType.isAnnotationPresent(StoredProcedures.class)) {
        final StoredProcedure[] procedures = entityType.getAnnotation(StoredProcedures.class).value();
        for (StoredProcedure procedure : procedures) {
            storedProcedures.add(getStoredProcedureMetadata(procedure));
        }
    }
    //noinspection unchecked
    if (!withMethods(entityType).keep(new GetterMethodFilter())
            .keep(new AnnotatedElementFilter(Column.class, JoinColumn.class))
            .keep(new AnnotatedElementFilter(Transient.class)).isEmpty()) {
        throw new TransientColumnFoundError(entityType);
    }
    final Collection<SequenceMetadata> sequences = new HashSet<SequenceMetadata>();
    final HashSet<ConstraintMetadata> constraints = new HashSet<ConstraintMetadata>();
    final AtomicReference<ColumnMetadata> versionColumn = new AtomicReference<ColumnMetadata>();
    //noinspection unchecked
    final List<Method> getters = withMethods(entityType).keep(new GetterMethodFilter()).list();
    final List<Method> filteredGetters = new ArrayList<Method>();
    for (Method getter : getters) {
        final PropertyAccessorFilter filter = new PropertyAccessorFilter(
                ReflectionUtils.getPropertyName(getter.getName()));
        final Method method = with(filteredGetters).find(filter);
        if (method == null) {
            filteredGetters.add(getter);
        } else if (method.getDeclaringClass().equals(getter.getDeclaringClass())) {
            filteredGetters.remove(method);
            filteredGetters.add(pickGetter(method, getter));
        }
    }
    getters.clear();
    getters.addAll(filteredGetters);
    //noinspection unchecked
    final Collection<ColumnMetadata> tableColumns = with(getters)
            .drop(new AnnotatedElementFilter(Transient.class)).drop(new AnnotatedElementFilter(OneToMany.class))
            .drop(new AnnotatedElementFilter(ManyToMany.class)).drop(new Filter<Method>() {
                @Override
                public boolean accepts(Method item) {
                    return item.isAnnotationPresent(OneToOne.class)
                            && !item.isAnnotationPresent(JoinColumn.class);
                }
            }).drop(new PropertyAccessorFilter(CLASS_PROPERTY))
            .transform(new Transformer<Method, ColumnMetadata>() {
                @Override
                public ColumnMetadata map(Method method) {
                    final JoinColumn joinColumn = method.getAnnotation(JoinColumn.class);
                    Column column = method.getAnnotation(Column.class);
                    if (column == null && joinColumn == null) {
                        //let's assume it is a column anyway
                        column = new DefaultColumn();
                    }
                    final String propertyName = ReflectionUtils.getPropertyName(method.getName());
                    if (column != null && joinColumn != null) {
                        throw new ColumnDefinitionError(
                                "Property " + propertyName + " is defined as both a column and a join column");
                    }
                    final Class<?> propertyType = method.getReturnType();
                    String name = column != null ? column.name() : joinColumn.name();
                    if (name.isEmpty()) {
                        name = propertyName;
                    }
                    final boolean nullable = column != null ? column.nullable() : joinColumn.nullable();
                    final int length = column != null ? column.length() : 0;
                    final int precision = column != null ? column.precision() : 0;
                    final int scale = column != null ? column.scale() : 0;
                    final ValueGenerationType generationType = determineValueGenerationType(method);
                    final String valueGenerator = determineValueGenerator(method);
                    final ColumnMetadata foreignColumn = joinColumn == null ? null
                            : determineForeignReference(method);
                    final int type = getColumnType(method, foreignColumn);
                    final Class<?> declaringClass = ReflectionUtils.getDeclaringClass(method);
                    if (method.isAnnotationPresent(BasicCollection.class)
                            && !(Collection.class.isAssignableFrom(method.getReturnType()))) {
                        throw new ColumnDefinitionError(
                                "Collection column must return a collection value: " + tableName + "." + name);
                    }
                    final ResolvedColumnMetadata columnMetadata = new ResolvedColumnMetadata(
                            new UnresolvedTableMetadata<E>(entityType), declaringClass, name, type,
                            propertyName, propertyType, nullable, length, precision, scale, generationType,
                            valueGenerator, foreignColumn, method.isAnnotationPresent(BasicCollection.class),
                            isComplex(method, foreignColumn));
                    if (foreignColumn != null) {
                        foreignKeys.add(name);
                    }
                    if (method.isAnnotationPresent(Id.class)) {
                        keyColumns.add(name);
                    }
                    if (method.isAnnotationPresent(SequenceGenerator.class)) {
                        final SequenceGenerator annotation = method.getAnnotation(SequenceGenerator.class);
                        sequences.add(new ImmutableSequenceMetadata(annotation.name(),
                                annotation.initialValue(), annotation.allocationSize()));
                    }
                    if (joinColumn != null) {
                        final RelationType relationType = getRelationType(method);
                        final CascadeMetadata cascadeMetadata = getCascadeMetadata(method);
                        final boolean isLazy = determineLaziness(method);
                        final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>(
                                declaringClass, columnMetadata.getPropertyName(), true, null, null, null,
                                relationType, cascadeMetadata, isLazy, null);
                        reference.setForeignColumn(foreignColumn);
                        foreignReferences.add(reference);
                    }
                    if (method.isAnnotationPresent(Version.class)) {
                        if (versionColumn.get() != null) {
                            throw new MultipleVersionColumnsError(entityType);
                        }
                        if (column != null) {
                            if (columnMetadata.isNullable()) {
                                throw new VersionColumnDefinitionError("Version column cannot be nullable: "
                                        + entityType.getCanonicalName() + "." + columnMetadata.getName());
                            }
                            versionColumn.set(columnMetadata);
                        } else {
                            throw new VersionColumnDefinitionError(
                                    "Only local columns can be used for optimistic locking");
                        }
                    }
                    return columnMetadata;
                }
            }).list();
    //handling one-to-many relations
    //noinspection unchecked
    withMethods(entityType).keep(new GetterMethodFilter())
            .drop(new AnnotatedElementFilter(Column.class, JoinColumn.class))
            .keep(new AnnotatedElementFilter(OneToMany.class)).each(new Processor<Method>() {
                @Override
                public void process(Method method) {
                    if (!Collection.class.isAssignableFrom(method.getReturnType())) {
                        throw new RelationDefinitionError(
                                "One to many relations must be collections. Error in " + method);
                    }
                    final OneToMany annotation = method.getAnnotation(OneToMany.class);
                    Class<?> foreignEntity = annotation.targetEntity().equals(void.class)
                            ? ((Class) ((ParameterizedType) method.getGenericReturnType())
                                    .getActualTypeArguments()[0])
                            : annotation.targetEntity();
                    String foreignColumnName = annotation.mappedBy();
                    final String propertyName = ReflectionUtils.getPropertyName(method.getName());
                    if (foreignColumnName.isEmpty()) {
                        //noinspection unchecked
                        final List<Method> list = withMethods(foreignEntity)
                                .keep(new AnnotatedElementFilter(JoinColumn.class))
                                .keep(new AnnotatedElementFilter(ManyToOne.class))
                                .keep(new MethodReturnTypeFilter(entityType)).list();
                        if (list.isEmpty()) {
                            throw new RelationDefinitionError(
                                    "No ManyToOne relations for " + entityType.getCanonicalName()
                                            + " were found on " + foreignEntity.getCanonicalName());
                        }
                        if (list.size() > 1) {
                            throw new RelationDefinitionError("Ambiguous one to many relationship on "
                                    + entityType.getCanonicalName() + "." + propertyName);
                        }
                        final Method foreignMethod = list.get(0);
                        final Column column = foreignMethod.getAnnotation(Column.class);
                        final JoinColumn joinColumn = foreignMethod.getAnnotation(JoinColumn.class);
                        foreignColumnName = column == null ? joinColumn.name() : column.name();
                        if (foreignColumnName.isEmpty()) {
                            foreignColumnName = ReflectionUtils.getPropertyName(foreignMethod.getName());
                        }
                    }
                    final List<OrderMetadata> ordering = getOrdering(foreignEntity,
                            method.getAnnotation(OrderBy.class));
                    //noinspection unchecked
                    final UnresolvedColumnMetadata foreignColumn = new UnresolvedColumnMetadata(
                            foreignColumnName,
                            new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity));
                    final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>(
                            ReflectionUtils.getDeclaringClass(method), propertyName, false, null, null, null,
                            getRelationType(method), getCascadeMetadata(method), determineLaziness(method),
                            ordering);
                    reference.setForeignColumn(foreignColumn);
                    foreignReferences.add(reference);
                }
            });
    //Handling one-to-one relations where the entity is not the owner of the relationship
    //noinspection unchecked
    withMethods(entityType).keep(new GetterMethodFilter()).keep(new AnnotatedElementFilter(OneToOne.class))
            .drop(new AnnotatedElementFilter(Column.class, JoinColumn.class)).each(new Processor<Method>() {
                @Override
                public void process(Method method) {
                    final OneToOne annotation = method.getAnnotation(OneToOne.class);
                    Class<?> foreignEntity = annotation.targetEntity().equals(void.class)
                            ? method.getReturnType()
                            : annotation.targetEntity();
                    final String propertyName = ReflectionUtils.getPropertyName(method.getName());
                    final DefaultRelationMetadata<E, Object> reference = new DefaultRelationMetadata<E, Object>(
                            ReflectionUtils.getDeclaringClass(method), propertyName, false, null, null, null,
                            getRelationType(method), getCascadeMetadata(method), determineLaziness(method),
                            null);
                    String foreignColumnName = annotation.mappedBy();
                    if (foreignColumnName.isEmpty()) {
                        //noinspection unchecked
                        final List<Method> methods = withMethods(foreignEntity).keep(new GetterMethodFilter())
                                .keep(new MethodReturnTypeFilter(entityType))
                                .keep(new AnnotatedElementFilter(OneToOne.class))
                                .keep(new AnnotatedElementFilter(Column.class, JoinColumn.class)).list();
                        if (methods.isEmpty()) {
                            throw new EntityDefinitionError(
                                    "No OneToOne relations were found on " + foreignEntity.getCanonicalName()
                                            + " for " + entityType.getCanonicalName());
                        }
                        if (methods.size() > 1) {
                            throw new EntityDefinitionError("Ambiguous OneToOne relation on "
                                    + entityType.getCanonicalName() + "." + propertyName);
                        }
                        final Method foreignMethod = methods.get(0);
                        final Column column = foreignMethod.getAnnotation(Column.class);
                        final JoinColumn joinColumn = foreignMethod.getAnnotation(JoinColumn.class);
                        foreignColumnName = column == null ? joinColumn.name() : column.name();
                        if (foreignColumnName.isEmpty()) {
                            foreignColumnName = ReflectionUtils.getPropertyName(foreignMethod.getName());
                        }
                    }
                    //noinspection unchecked
                    reference.setForeignColumn(new UnresolvedColumnMetadata(foreignColumnName,
                            new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity)));
                    foreignReferences.add(reference);
                }
            });
    final HashSet<NamedQueryMetadata> namedQueries = new HashSet<NamedQueryMetadata>();
    if (entityType.isAnnotationPresent(SequenceGenerator.class)) {
        final SequenceGenerator annotation = entityType.getAnnotation(SequenceGenerator.class);
        sequences.add(new ImmutableSequenceMetadata(annotation.name(), annotation.initialValue(),
                annotation.allocationSize()));
    }
    //finding orderings
    //noinspection unchecked
    final List<OrderMetadata> ordering = withMethods(entityType).keep(new AnnotatedElementFilter(Column.class))
            .keep(new AnnotatedElementFilter(Order.class)).sort(new Comparator<Method>() {
                @Override
                public int compare(Method firstMethod, Method secondMethod) {
                    final Order first = firstMethod.getAnnotation(Order.class);
                    final Order second = secondMethod.getAnnotation(Order.class);
                    return ((Integer) first.priority()).compareTo(second.priority());
                }
            }).transform(new Transformer<Method, OrderMetadata>() {
                @Override
                public OrderMetadata map(Method input) {
                    final Column column = input.getAnnotation(Column.class);
                    String columnName = column.name().isEmpty()
                            ? ReflectionUtils.getPropertyName(input.getName())
                            : column.name();
                    ColumnMetadata columnMetadata = with(tableColumns).find(new ColumnNameFilter(columnName));
                    if (columnMetadata == null) {
                        columnMetadata = with(tableColumns).find(new ColumnPropertyFilter(columnName));
                    }
                    if (columnMetadata == null) {
                        throw new NoSuchColumnError(entityType, columnName);
                    }
                    return new ImmutableOrderMetadata(columnMetadata, input.getAnnotation(Order.class).value());
                }
            }).list();
    final ResolvedTableMetadata<E> tableMetadata = new ResolvedTableMetadata<E>(entityType, schema, tableName,
            constraints, tableColumns, namedQueries, sequences, storedProcedures, foreignReferences,
            versionColumn.get(), ordering);
    if (!keyColumns.isEmpty()) {
        constraints.add(new PrimaryKeyConstraintMetadata(tableMetadata,
                with(keyColumns).transform(new Transformer<String, ColumnMetadata>() {
                    @Override
                    public ColumnMetadata map(String columnName) {
                        return getColumnMetadata(columnName, tableColumns, entityType);
                    }
                }).list()));
    }
    if (entityType.isAnnotationPresent(NamedNativeQueries.class)) {
        final NamedNativeQuery[] queries = entityType.getAnnotation(NamedNativeQueries.class).value();
        for (NamedNativeQuery query : queries) {
            namedQueries.add(new ImmutableNamedQueryMetadata(query.name(), query.query(), tableMetadata,
                    QueryType.NATIVE));
        }
    } else if (entityType.isAnnotationPresent(NamedNativeQuery.class)) {
        final NamedNativeQuery query = entityType.getAnnotation(NamedNativeQuery.class);
        namedQueries.add(
                new ImmutableNamedQueryMetadata(query.name(), query.query(), tableMetadata, QueryType.NATIVE));
    }
    constraints
            .addAll(with(uniqueColumns).sort().transform(new Transformer<Set<String>, Set<ColumnMetadata>>() {
                @Override
                public Set<ColumnMetadata> map(Set<String> columns) {
                    return with(columns).transform(new Transformer<String, ColumnMetadata>() {
                        @Override
                        public ColumnMetadata map(String columnName) {
                            return getColumnMetadata(columnName, tableColumns, entityType);
                        }
                    }).set();
                }
            }).transform(new Transformer<Set<ColumnMetadata>, UniqueConstraintMetadata>() {
                @Override
                public UniqueConstraintMetadata map(Set<ColumnMetadata> columns) {
                    return new UniqueConstraintMetadata(tableMetadata, columns);
                }
            }).list());
    constraints.addAll(with(foreignKeys).sort().transform(new Transformer<String, ColumnMetadata>() {
        @Override
        public ColumnMetadata map(String columnName) {
            return getColumnMetadata(columnName, tableColumns, entityType);
        }
    }).transform(new Transformer<ColumnMetadata, ForeignKeyConstraintMetadata>() {
        @Override
        public ForeignKeyConstraintMetadata map(ColumnMetadata columnMetadata) {
            return new ForeignKeyConstraintMetadata(tableMetadata, columnMetadata);
        }
    }).list());
    //going after many-to-many relations
    //noinspection unchecked
    withMethods(entityType).drop(new AnnotatedElementFilter(Column.class, JoinColumn.class))
            .keep(new GetterMethodFilter()).forThose(new Filter<Method>() {
                @Override
                public boolean accepts(Method item) {
                    return item.isAnnotationPresent(ManyToMany.class);
                }
            }, new Processor<Method>() {
                @Override
                public void process(Method method) {
                    final ManyToMany annotation = method.getAnnotation(ManyToMany.class);
                    Class<?> foreignEntity = annotation.targetEntity().equals(void.class)
                            ? ((Class) ((ParameterizedType) method.getGenericReturnType())
                                    .getActualTypeArguments()[0])
                            : annotation.targetEntity();
                    String foreignProperty = annotation.mappedBy();
                    if (foreignProperty.isEmpty()) {
                        //noinspection unchecked
                        final List<Method> methods = withMethods(foreignEntity).keep(new GetterMethodFilter())
                                .keep(new AnnotatedElementFilter(ManyToMany.class)).list();
                        if (methods.isEmpty()) {
                            throw new EntityDefinitionError(
                                    "Failed to locate corresponding many-to-many relation on "
                                            + foreignEntity.getCanonicalName());
                        }
                        if (methods.size() == 1) {
                            throw new EntityDefinitionError("Ambiguous many-to-many relationship defined");
                        }
                        foreignProperty = ReflectionUtils.getPropertyName(methods.get(0).getName());
                    }
                    final List<OrderMetadata> ordering = getOrdering(foreignEntity,
                            method.getAnnotation(OrderBy.class));
                    //noinspection unchecked
                    foreignReferences.add(new DefaultRelationMetadata<E, Object>(
                            ReflectionUtils.getDeclaringClass(method),
                            ReflectionUtils.getPropertyName(method.getName()), false, tableMetadata, null,
                            new UnresolvedColumnMetadata(foreignProperty,
                                    new UnresolvedTableMetadata<Object>((Class<Object>) foreignEntity)),
                            RelationType.MANY_TO_MANY, getCascadeMetadata(method), determineLaziness(method),
                            ordering));
                }
            });
    return tableMetadata;
}