Example usage for java.util SortedSet add

List of usage examples for java.util SortedSet add

Introduction

In this page you can find the example usage for java.util SortedSet add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:net.sourceforge.fenixedu.domain.student.Registration.java

final public StudentCurricularPlan getLastStudentDegreeCurricularPlansByDegree(Degree degree) {
    final SortedSet<StudentCurricularPlan> result = new TreeSet<StudentCurricularPlan>(
            StudentCurricularPlan.DATE_COMPARATOR);
    for (DegreeCurricularPlan degreeCurricularPlan : this.getDegreeCurricularPlans()) {
        if (degreeCurricularPlan.getDegree() == degree) {
            result.add(this.getStudentCurricularPlan(degreeCurricularPlan));
        }//from  ww  w.ja v  a 2s. co m
    }
    return result.last();

}

From source file:gov.nasa.jpl.magicdraw.projectUsageIntegrity.graph.SSCAEProjectUsageGraph.java

protected void createGraph() throws RemoteException {
    final List<IProject> allSortedProjects = new ArrayList<IProject>();
    allSortedProjects.addAll(ProjectUtilities.getAllProjects(this.project));
    Collections.sort(allSortedProjects, IPROJECT_COMPARATOR);
    boolean performanceLoggingEnabled = ProjectUsageIntegrityPlugin.getInstance().isPerformanceLoggingEnabled();
    int width = Integer.toString(allSortedProjects.size()).length();

    Long currentTime;//from   w  w w  . j  a v  a 2  s  . c  o m
    Long previousTime = System.currentTimeMillis();

    MDAbstractProject vPrimary = createVertex(this.primaryProject, width);
    moduleOrProject2SharedPackages.put(vPrimary, new HashSet<Package>());

    this.isTemplate = vPrimary.isLocalTemplate();
    for (IProject aProject : allSortedProjects) {
        MDAbstractProject vAttached = createVertex(aProject, width);
        moduleOrProject2SharedPackages.put(vAttached, new HashSet<Package>());
    }

    for (Package sharedPackage : sharedPackage2references.keySet()) {
        IProject ip = ProjectUtilities.getProject(sharedPackage);
        MDAbstractProject v = vertexMap.get(ip);
        moduleOrProject2SharedPackages.get(v).add(sharedPackage);
    }

    for (MDAbstractProject v : moduleOrProject2SharedPackages.keySet()) {
        boolean hasDeprecated = false;
        boolean hasIncubator = false;
        boolean hasRecommended = false;
        for (Package vSharedPackage : moduleOrProject2SharedPackages.get(v)) {
            hasDeprecated |= sharedPackages_classified_DEPRECATED.contains(vSharedPackage);
            hasIncubator |= sharedPackages_classified_INCUBATOR.contains(vSharedPackage);
            hasRecommended |= sharedPackages_classified_RECOMMENDED.contains(vSharedPackage);
        }
        if ((hasDeprecated && hasIncubator) || (hasDeprecated && hasRecommended)
                || (hasIncubator && hasRecommended))
            moduleOrProjectWithInconsistentlyClassifiedSharedPackages.add(v);
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Create Graph: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    for (IProject aProject : allSortedProjects) {
        MDAbstractProject p1 = lookupVertex(aProject);
        List<MDAbstractProjectUsage> p1Usages = new ArrayList<MDAbstractProjectUsage>();

        AbstractProject ap = (AbstractProject) aProject;
        if (ap.isProjectAvailable() && !this.excludedProjectNames.contains(aProject.getName())) {
            IDecompositionModel dm = (IDecompositionModel) ap.getService(IDecompositionModel.class);
            if (dm.isAvailable()) {
                IProjectUsageManager pum = (IProjectUsageManager) ap.getService(IProjectUsageManager.class);
                for (ProjectUsage pu : dm.getDecompositionProject().getProjectUsages()) {
                    if (pu != null) {
                        IProject up = pum.getProject(pu);
                        if (up instanceof AbstractAttachedProject) {
                            AbstractAttachedProject aap = (AbstractAttachedProject) up;
                            MDAbstractProject p2 = lookupVertex(aap);
                            MDAbstractProjectUsage e = null;
                            if (aap instanceof TeamworkAttachedProject) {
                                TeamworkAttachedProject tap = (TeamworkAttachedProject) aap;
                                e = createTeamworkEdge(p1, p2, pu, tap);
                            } else if (aap instanceof LocalAttachedProject) {
                                LocalAttachedProject lap = (LocalAttachedProject) aap;
                                e = createLocalEdge(p1, p2, pu, lap);
                            } else
                                throw new IllegalArgumentException(
                                        "unhandled AbstractAttachedProject: " + aap.getClass().getName());
                            p1Usages.add(e);
                            createEdge(e);
                            vertexUsedByEdges.get(p2).add(e);
                            if (!e.isResolved())
                                unresolvedUsageEdges.add(e);
                        }
                    }
                }
            }
        }

        Collections.sort(p1Usages, PROJECT_USAGE_EDGE_COMPARATOR);
        vertexUsageEdges.put(p1, p1Usages);

    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Assign type of nodes: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    StrongConnectivityInspector<MDAbstractProject, MDAbstractProjectUsage> detector = new StrongConnectivityInspector<MDAbstractProject, MDAbstractProjectUsage>(
            projectUsageDirectedMultigraph);
    List<DirectedSubgraph<MDAbstractProject, MDAbstractProjectUsage>> stronglyConnectedSubgraphs = detector
            .stronglyConnectedSubgraphs();

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Check circular dependencies: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    for (DirectedSubgraph<MDAbstractProject, MDAbstractProjectUsage> stronglyConnectedSubgraph : stronglyConnectedSubgraphs) {
        Set<MDAbstractProject> vertexSubset = stronglyConnectedSubgraph.vertexSet();
        Set<MDAbstractProjectUsage> edgeSubset = stronglyConnectedSubgraph.edgeSet();
        if (edgeSubset.isEmpty())
            continue;

        for (MDAbstractProject v : vertexSubset)
            stronglyConnectedVertices.add(v);
        for (MDAbstractProjectUsage e : edgeSubset)
            stronglyConnectedEdges.add(e);
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Record circular dependencies: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    for (IProject aProject : allSortedProjects) {
        MDAbstractProject p2 = lookupVertex(aProject);
        if (p2.isProjectMissing() && !(p2 instanceof MDLocalPrimaryProject))
            missingProjects.add(p2);

        // TODO root project needs to a tws project
        if ((this.primaryProject instanceof TeamworkPrimaryProject) && p2 instanceof MDLocalAttachedProject
                && !(p2.equals(this.primaryProject))) {

            boolean isStandardSystemProfile = false;
            try {
                isStandardSystemProfile = ProjectUtilities.isStandardSystemProfile(aProject);
            } catch (NullPointerException e) {
                // Can occur if iprofile is null?

                pluginLog.error("PUIC - Not able to find project " + aProject.getName()
                        + ", cannot determine isStandardSystemProfile()");
            }

            if (!isStandardSystemProfile)
                missingSSPProjects.add(p2);
        }

        List<MDAbstractProjectUsage> p2UsedBy = vertexUsedByEdges.get(p2);
        Collections.sort(p2UsedBy, PROJECT_USAGE_EDGE_COMPARATOR);

        Map<String, List<MDAbstractProjectUsage>> signature2UsedBy = new HashMap<String, List<MDAbstractProjectUsage>>();
        for (MDAbstractProjectUsage p12 : p2UsedBy) {
            String signature = p12.getSignature();
            if (!signature2UsedBy.containsKey(signature))
                signature2UsedBy.put(signature, new ArrayList<MDAbstractProjectUsage>());
            signature2UsedBy.get(signature).add(p12);
        }

        Set<String> distinctSignatures = signature2UsedBy.keySet();
        int count = distinctSignatures.size();

        if (count == 0)
            continue;

        if (count == 1) {
            String sig = distinctSignatures.iterator().next();
            for (MDAbstractProjectUsage usage : signature2UsedBy.get(sig)) {
                String label = "OK";
                if (!usage.isValidUsage()) {
                    invalidUsageEdges.add(usage);
                    label = "INVALID";
                    if (stronglyConnectedEdges.contains(usage))
                        label += ", CYCLIC";
                } else {
                    if (stronglyConnectedEdges.contains(usage))
                        label = "CYCLIC";
                }
                vertexUsageConsistencyLabel.put(p2, distinctSignatures.iterator().next());
                usage.setUsageConsistencyLabel(label);
            }
        } else {
            int c = 0;
            for (String sig : distinctSignatures) {
                String label = String.format("INCONSISTENT[%d/%d]", ++c, count);
                for (MDAbstractProjectUsage usage : signature2UsedBy.get(sig)) {
                    String ulabel = label;
                    if (stronglyConnectedEdges.contains(usage))
                        ulabel += ", CYCLIC";
                    if (!usage.isValidUsage()) {
                        ulabel += ", INVALID";
                        invalidUsageEdges.add(usage);
                    }
                    inconsistentUsageEdges.add(usage);
                    inconsistentlyUsedVertices.add(usage.getTarget());
                    usage.setUsageConsistencyLabel(ulabel);
                }
            }
        }
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Check consistency of usages: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    IPrimaryProject sourceP = this.primaryProject;
    Set<IAttachedProject> missingDirectProjectUsages = new HashSet<IAttachedProject>();
    missingDirectProjectUsages.addAll(ProjectUtilities.getAllAttachedProjects(sourceP));
    IDecompositionModel dm = (IDecompositionModel) sourceP.getService(IDecompositionModel.class);
    if (dm.isAvailable()) {
        IProjectUsageManager pum = (IProjectUsageManager) sourceP.getService(IProjectUsageManager.class);
        for (ProjectUsage usageRel : dm.getDecompositionProject().getProjectUsages()) {
            if (null != usageRel) {
                IProject usedP = pum.getProject(usageRel);
                if (!(usedP instanceof IAttachedProject))
                    continue;
                IAttachedProject targetP = (IAttachedProject) usedP;
                missingDirectProjectUsages.remove(targetP);
            }
        }
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Check missing usages: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    if (!missingDirectProjectUsages.isEmpty()) {
        MDAbstractProject u = lookupVertex(sourceP);
        for (IAttachedProject missingP : missingDirectProjectUsages) {
            if (vertexMap.containsKey(missingP)) {
                MDAbstractProject v = vertexMap.get(missingP);
                if (!inconsistentlyUsedVertices.contains(v)) {
                    IProjectDecompositionManager missingDM = ProjectUtilitiesInternal
                            .getDecompositionManager(missingP);
                    Map<IProject, ProjectAttachmentConfiguration> attachingProjectsMap = missingDM
                            .getAttachingProjects();
                    if (!attachingProjectsMap.isEmpty() && !attachingProjectsMap.containsKey(sourceP)) {
                        ProjectAttachmentConfiguration config = attachingProjectsMap.values().iterator().next();
                        missingDirectAttachments.put(missingP, config);
                        MDAbstractProjectUsage e = null;

                        if (missingP instanceof LocalAttachedProject) {
                            e = createLocalMissingEdge(u, v, (LocalAttachedProject) missingP);
                        } else if (missingP instanceof TeamworkAttachedProject) {
                            e = createTeamworkMissingEdge(u, v, (TeamworkAttachedProject) missingP);
                        } else
                            throw new IllegalArgumentException(
                                    "unhandled AbstractAttachedProject: " + missingP.getClass().getName());
                        createEdge(e);
                    }
                }
            }
        }
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Check missing direct attachments: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    // force loading all diagrams only if there are proxies so that the user can find the proxy usage references in the diagrams.
    final Collection<DiagramPresentationElement> projectDiagrams = project.getDiagrams();
    diagramCount = projectDiagrams.size();

    final ProxyManager proxyManager = project.getProxyManager();
    if (!proxyManager.getProxies().isEmpty() && plugin.isLoadDiagarmsProperty()) {

        final Set<DiagramPresentationElement> unloadedDPEs = new HashSet<DiagramPresentationElement>();
        for (DiagramPresentationElement dpe : projectDiagrams) {
            if (dpe.isLoaded())
                continue;
            unloadedDPEs.add(dpe);
        }

        if (!unloadedDPEs.isEmpty()) {
            final File logTraceContractsDir = plugin.getLogTraceContractsFolder();
            final File diagramProxyUsageMonitorSpec = (null == logTraceContractsDir) ? null
                    : new File(logTraceContractsDir.getAbsolutePath() + File.separator
                            + "diagramProxyUsageMonitor.txt");
            final String diagramProxyUsageMonitorPath = (null == diagramProxyUsageMonitorSpec
                    || !diagramProxyUsageMonitorSpec.canRead()) ? null
                            : diagramProxyUsageMonitorSpec.getAbsolutePath();

            new RunnableSessionWrapper(
                    String.format("Loading %d diagrams('%s')", unloadedDPEs.size(), project.getName())) {

                @Override
                public void run() {
                    boolean wasLocked = EnvironmentLockManager.isLocked();
                    try {
                        EnvironmentLockManager.setLocked(true);
                        for (final DiagramPresentationElement diagramPresentationElement : unloadedDPEs) {
                            String sessionLabel = String.format("LoadDiagram('%s' {ID=%s})",
                                    diagramPresentationElement.getDiagram().getQualifiedName(),
                                    diagramPresentationElement.getID());
                            RunnableSessionWrapper sessionWrapper = new RunnableSessionWrapper(sessionLabel) {

                                @Override
                                public void run() {
                                    diagramPresentationElement.ensureLoaded();
                                }
                            };

                            String sessionLogFile = appender.getFileLocation(sessionWrapper.sessionID);
                            if (null != diagramProxyUsageMonitorPath) {
                                Monitor sessionMonitor = new Monitor(diagramProxyUsageMonitorPath,
                                        sessionLogFile);
                                SessionReport report = sessionMonitor.verifyWholeSession(sessionLabel);
                                if (report.numberOfViolations() > 0) {
                                    diagram2sessionReport.put(diagramPresentationElement, report);
                                }
                            }
                        }
                    } finally {
                        EnvironmentLockManager.setLocked(wasLocked);
                    }
                }
            };
        }

        for (DiagramPresentationElement dpe : projectDiagrams) {
            List<PresentationElement> manipulatedElements = new ArrayList<PresentationElement>();
            dpe.collectSubPresentationElements(manipulatedElements);
            Set<Element> dpeProxies = new HashSet<Element>();
            for (PresentationElement manipulatedElement : manipulatedElements) {
                Element e = manipulatedElement.getElement();
                if (proxyManager.isElementProxy(e)) {
                    dpeProxies.add(e);
                }
            }
            if (dpeProxies.isEmpty())
                continue;
            diagram2proxyUsages.put(dpe, dpeProxies);
        }
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Check proxies: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();

    }
    ;

    // Check profiles (This could be slow so need to be careful)
    List<Profile> projectProfiles = StereotypesHelper.getAllProfiles(project);

    if (!projectProfiles.isEmpty()) {
        HashMap<String, Profile> userProfileNames = new HashMap<String, Profile>();
        HashMap<String, Profile> sspProfileNames = new HashMap<String, Profile>();
        HashMap<String, Profile> profileURIs = new HashMap<String, Profile>();

        for (Profile profile : projectProfiles) {
            IProject iprofile = ProjectUtilities.getProject(profile);
            boolean isStandardSystemProfile = false;
            try {
                isStandardSystemProfile = ProjectUtilities.isStandardSystemProfile(iprofile);
            } catch (NullPointerException e) {
                // Can occur if iprofile is null?

                pluginLog.error("PUIC - Not able to find iprofile " + profile.getName()
                        + ", cannot determine isStandardSystemProfile()");
            }

            String profileURI = profile.getURI();

            if (isStandardSystemProfile) {
                if (sspProfileNames.containsKey(profile.getName())) {
                    nonUniqueNamesSSPProfiles.put(profile, sspProfileNames.get(profile.getName()));
                }
                sspProfileNames.put(profile.getName(), profile);
            } else {
                if (userProfileNames.containsKey(profile.getName())) {
                    nonUniqueNamesUserProfiles.put(profile, userProfileNames.get(profile.getName()));
                }
                if (sspProfileNames.containsKey(profile.getName())) {
                    nonUniqueNamesUserProfiles.put(profile, sspProfileNames.get(profile.getName()));
                }
                userProfileNames.put(profile.getName(), profile);
            }

            if (profileURIs.containsKey(profileURI)) {
                nonUniqueURIProfiles.put(profile, profileURIs.get(profileURI));
            }

            for (String URI : profileURIs.keySet()) {
                if (profileURI.length() == 0) {
                    break;
                }

                if (URI.length() == 0) {
                    continue;
                }

                if (URI.length() <= profileURI.length()) {
                    if (SSCAEProfileValidation.appendSeparator(profileURI)
                            .startsWith(SSCAEProfileValidation.appendSeparator(URI))) {
                        nonUniqueURIProfiles.put(profile, profileURIs.get(URI));
                        break;
                    }
                } else {
                    if (SSCAEProfileValidation.appendSeparator(URI)
                            .startsWith(SSCAEProfileValidation.appendSeparator(profileURI))) {
                        nonUniqueURIProfiles.put(profile, profileURIs.get(URI));
                        break;
                    }
                }
            }

            if (!profileURI.equals("")) {
                profileURIs.put(profileURI, profile);
            } else {
                // may want to check to make sure all profiles have URIs?
            }
        }
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Check uniqueness of profiles: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    // Check packages (This will be slow, need to be very careful)      
    if (!this.managedSharedPackages.isEmpty()) {
        HashMap<String, Package> packageURIs = new HashMap<String, Package>();

        for (Package pack : this.managedSharedPackages) {
            String packageURI = pack.getURI();

            if (packageURIs.containsKey(packageURI)) {
                nonUniqueURIPackages.put(pack, packageURIs.get(packageURI));
            }

            for (String URI : packageURIs.keySet()) {
                if (packageURI.length() == 0) {
                    break;
                }

                if (URI.length() == 0) {
                    continue;
                }

                if (URI.length() <= packageURI.length()) {
                    if (SSCAEProfileValidation.appendSeparator(packageURI)
                            .startsWith(SSCAEProfileValidation.appendSeparator(URI))) {
                        if (!MD_EXCLUDE_URI_CHECK_PROFILES_AND_PACKAGES.contains(pack.getQualifiedName())) {
                            nonUniqueURIPackages.put(pack, packageURIs.get(URI));
                        }
                        break;
                    }
                } else {
                    if (SSCAEProfileValidation.appendSeparator(URI)
                            .startsWith(SSCAEProfileValidation.appendSeparator(packageURI))) {
                        if (!MD_EXCLUDE_URI_CHECK_PROFILES_AND_PACKAGES.contains(pack.getQualifiedName())) {
                            nonUniqueURIPackages.put(pack, packageURIs.get(URI));
                        }
                        break;
                    }
                }
            }

            if (!packageURI.equals("")) {
                packageURIs.put(packageURI, pack);
            } else {
                // may want to check to make sure all profiles have URIs?
            }
        }
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Check uniqueness of packages: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    final Collection<Element> proxies = proxyManager.getProxies();
    proxyCount = proxies.size();

    for (Element proxy : proxies) {
        Assert.isTrue(proxyManager.isElementProxy(proxy));

        if (proxyManager.isGhostProxy(proxy)) {
            Element owner = proxy.getOwner();
            while (null != owner && proxyManager.isElementProxy(owner)) {
                owner = owner.getOwner();
            }
            if (null == owner) {
                proxyGhostOtherCount.add(proxy);
            } else {
                proxyGhostOkCount++;
                if (!owner2proxiesMap.containsKey(owner))
                    owner2proxiesMap.put(owner, new TreeSet<Element>(ELEMENT_ID_COMPARATOR));
                SortedSet<Element> ownedProxies = owner2proxiesMap.get(owner);
                ownedProxies.add(proxy);
                owner2proxiesMap.put(owner, ownedProxies);
            }
            IAttachedProject p = proxyManager.getModuleWithMissingShare(proxy);
            MDAbstractProject ap = (null != p) ? vertexMap.get(p) : null;
            if (null != p) {
                moduleWithMissingShares.add(ap);
            }
        } else {
            IAttachedProject proxyProject = ProjectUtilities.getAttachedProject(proxy);

            // @see https://support.nomagic.com/browse/MDUMLCS-9157
            // for now, we will assume that if the proxyProject is not loaded, then MD could load it.
            // if we explicitly check if the proxyProject can be loaded --i.e. proxyProject.canLoad() --
            // then we may induce a deadlock if the graph analysis is performed during the ProjectEventListenerAdapter#projectOpened() callback.
            // This happened for OPALS!

            if (null != proxyProject && !((AbstractAttachedProject) proxyProject).isLoaded()) {
                proxyUnloadedOkCount++;
                if (!unloaded2proxiesMap.containsKey(proxyProject))
                    unloaded2proxiesMap.put(proxyProject, new TreeSet<Element>(ELEMENT_ID_COMPARATOR));
                SortedSet<Element> proxyProjectElements = unloaded2proxiesMap.get(proxyProject);
                proxyProjectElements.add(proxy);
            } else {
                proxyUnloadedOtherCount.add(proxy);
            }
        }
    }

    if (performanceLoggingEnabled) {
        currentTime = System.currentTimeMillis();
        pluginLog.info("PUIC -- Check for unloaded projects: " + (currentTime - previousTime) + " (ms)");
        previousTime = System.currentTimeMillis();
    }
    ;

    // Elaborate the graph diagnostics summary
    boolean notifySSCAE = false;

    gDiagnostic.append(String.format("'%s'\nSSCAEProjectUsageGraph(Vertices=%d, Edges=%d, Diagrams=%d)",
            project.getName(), projectUsageDirectedMultigraph.vertexSet().size(),
            projectUsageDirectedMultigraph.edgeSet().size(), diagramCount));

    if (helper.collaborationIntegrityInvariantTransactionMonitor.illegalTransactionsDetected()) {
        gDiagnostic.append(
                String.format("\nERROR: model *may* be compromised due to illegal teamwork transactions"));
    } else {
        gDiagnostic.append(String.format("\n   OK: no illegal teamwork transactions detected"));
    }

    if (isProjectMissingSystemOrStandardProfileFlag()) {
        gDiagnostic.append(
                String.format("\nERROR: this project should have the System/Standard Profile flag set"));
    }

    if (localModulesWithTeamworkIDs.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: no local modules with teamwork project IDs"));
    } else {
        gDiagnostic.append(String.format("\nWARNING: %d local modules have a teamwork project ID",
                localModulesWithTeamworkIDs.size()));
        for (MDAbstractProject localModuleWithTeamworkID : localModulesWithTeamworkIDs) {
            gMessages.append(
                    String.format("\nlocal module with teamwork ID: %s", localModuleWithTeamworkID.getName()));
        }
    }

    if (missingDirectAttachments.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: no missing direct ProjectUsage mount attachments"));
    } else {
        gDiagnostic.append(
                String.format("\nERROR: this project is missing %d direct ProjectUsage mount attachments",
                        missingDirectAttachments.size()));
    }

    if (unresolvedUsageEdges.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: no unresolved ProjectUsage relationships"));
    } else {
        gDiagnostic.append(String.format(
                "\nERROR: there are %d unresolved ProjectUsage relationships -- *** please save/commit and re-open the project to force resolution ***",
                unresolvedUsageEdges.size()));
    }

    if (proxyCount == 0) {
        gDiagnostic.append(String.format("\n   OK: no proxies detected"));
    } else {
        gDiagnostic.append(String.format("\nERROR: %s proxies detected", proxyCount));
        if (proxyGhostOkCount == 0)
            gDiagnostic.append(String.format("\n   OK: - no proxies for recovered elements"));
        else
            gDiagnostic
                    .append(String.format("\nERROR: - %s proxies for recovered elements", proxyGhostOkCount));
        if (!proxyGhostOtherCount.isEmpty()) {
            gDiagnostic.append(
                    String.format("\nERROR: - %s proxies for non-recovered elements (*** Notify SSCAE ***)",
                            proxyGhostOtherCount.size()));
            notifySSCAE = true;
        }
        if (proxyUnloadedOkCount == 0)
            gDiagnostic.append(String.format("\n   OK: - no proxies for missing elements in loadable modules"));
        else
            gDiagnostic.append(String.format("\nERROR: - %s proxies for missing elements in loadable modules",
                    proxyUnloadedOkCount));
        if (!proxyUnloadedOtherCount.isEmpty()) {
            gDiagnostic.append(
                    String.format("\nERROR: - %s proxies for missing elements elsewhere (*** Notify SSCAE ***)",
                            proxyUnloadedOtherCount.size()));
            notifySSCAE = true;
        }
        if (plugin.isLoadDiagarmsProperty()) {
            if (diagram2proxyUsages.isEmpty()) {
                gDiagnostic.append(String.format("\n   OK: none of the %d diagrams have proxy usage problems",
                        diagramCount));
            } else {
                gDiagnostic.append(String.format("\nERROR: %d / %d diagrams have proxy usage problems",
                        diagram2proxyUsages.size(), diagramCount));
            }
        }
    }

    if (missingProjects.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: all projects are available"));
    } else {
        gDiagnostic.append(String.format("\nERROR: %d projects are missing", missingProjects.size()));
        for (MDAbstractProject missingProject : missingProjects) {
            gMessages.append(String.format("\n missing project: %s", missingProject.getName()));
        }
    }

    if (missingSSPProjects.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: all local projects have SSP flag"));
    } else {
        gDiagnostic.append(String.format("\nERROR: %d projects are missing the SSP flag",

                missingSSPProjects.size()));
        gMessages.append(
                String.format("\nERROR: %d projects are missing the SS flag", missingSSPProjects.size()));

        for (MDAbstractProject missingProject : missingSSPProjects) {
            gMessages.append(String.format("\n project missing SSP flag: %s", missingProject.getName()));
        }
    }

    if (moduleWithMissingShares.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: all projects have no missing shares"));
    } else {
        gDiagnostic.append(
                String.format("\nERROR: %d projects have missing shares", moduleWithMissingShares.size()));
        for (MDAbstractProject missingShares : moduleWithMissingShares) {
            gMessages.append(String.format("\n module with missing shares: %s", missingShares.getName()));
        }
    }

    if (shouldBeSystemOrStandardProfile.isEmpty()) {
        gDiagnostic.append(String.format(
                "\n   OK: all local projects used from MD's install folder have the Standard/System Profile flag set"));
    } else {
        gDiagnostic.append(String.format(
                "\nERROR: %d projects used from MD's install folder do not have the Standard/System Profile flag set",
                shouldBeSystemOrStandardProfile.size()));
        for (MDAbstractProject shouldBeSSP : shouldBeSystemOrStandardProfile) {
            gMessages.append(String.format(
                    "\n missing Standard/System Profile flag for module in MD's install folder: %s",
                    shouldBeSSP.getName()));
        }
    }

    if (nonUniqueNamesSSPProfiles.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: all SSP profiles have unique names"));

    } else {
        gDiagnostic.append(String.format("\nWARNING: %d SSP profiles have non-unique names",
                nonUniqueNamesSSPProfiles.size()));
        for (Profile p : nonUniqueNamesSSPProfiles.keySet()) {
            gMessages.append(String.format("\n SSP profile with non-unique name: %s", p.getQualifiedName()));
        }
    }

    if (nonUniqueNamesUserProfiles.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: all user profiles have unique names"));

    } else {
        gDiagnostic.append(String.format("\nERROR: %d user profiles have non-unique names",
                nonUniqueNamesUserProfiles.size()));
        for (Profile p : nonUniqueNamesUserProfiles.keySet()) {
            gMessages.append(String.format("\n user profile with non-unique name: %s", p.getQualifiedName()));
        }
    }

    if (nonUniqueURIProfiles.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: all profiles have unique URIs"));
    } else {
        gDiagnostic.append(
                String.format("\nERROR: %d profiles have non-unique URIs", nonUniqueURIProfiles.size()));
        for (Profile p : nonUniqueURIProfiles.keySet()) {
            gMessages.append(String.format("\n profile with non-unique URI: %s (URI=%s)", p.getQualifiedName(),
                    p.getURI()));
        }
    }

    if (nonUniqueURIPackages.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: all packages have unique URIs"));
    } else {
        gDiagnostic.append(
                String.format("\nERROR: %d packages have non-unique URIs", nonUniqueURIPackages.size()));
        for (Package p : nonUniqueURIPackages.keySet()) {
            gMessages.append(String.format("\n package with non-unique URI: %s (URI=%s)", p.getQualifiedName(),
                    p.getURI()));
        }
    }

    if (stronglyConnectedVertices.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: project usage mount relationships are acyclic"));
    } else {
        gDiagnostic.append(String.format(
                "\nERROR: %d projects are involved in %d project usage mount cyclic relationships",
                stronglyConnectedVertices.size(), stronglyConnectedEdges.size()));
    }

    if (inconsistentUsageEdges.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: project usage mount relationships are consistent"));
    } else {
        gDiagnostic.append(String.format("\nERROR: %d project usage mount relationships are inconsistent",
                inconsistentUsageEdges.size()));
    }

    if (inconsistentlyUsedVertices.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: all projects are used consistently"));
    } else {
        gDiagnostic.append(String.format("\nERROR: %d projects are used inconsistently",
                inconsistentlyUsedVertices.size()));
    }

    if (invalidUsageEdges.isEmpty()) {
        gDiagnostic.append(String.format("\n   OK: project usage mount relationships are valid"));
    } else {
        gDiagnostic.append(String.format("\nERROR: %d project usage mount relationships are invalid",
                invalidUsageEdges.size()));
    }

    if (noSharedPackage_constrainedAs_WARNING_fromUsages && noSharedPackage_constrainedAs_ERROR_fromUsages)
        gDiagnostic.append(String.format("\n   OK: all shared package usage constraints are consistent"));

    for (Package p : sharedPackages_constrainedAs_OK_fromUsages.keySet()) {
        Set<Usage> usages = sharedPackages_constrainedAs_OK_fromUsages.get(p);
        if (usages.isEmpty())
            continue;
        for (Usage usage : usages) {
            if (usageConstraint2usingPackage.containsKey(usage)
                    && p.equals(usageConstraint2sharedPackage.get(usage))) {
                Package source = usageConstraint2usingPackage.get(usage);
                IProject ip1 = ProjectUtilities.getProject(source);
                MDAbstractProject v1 = vertexMap.get(ip1);

                IProject ip2 = ProjectUtilities.getProject(p);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectUsageConstraint e = new MDProjectUsageConstraint(
                            MDProjectUsageConstraint.UsageConstraintLevel.OK, p.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    e.setIndex(e.getLabel() + ":" + v1.getIndex() + "=>" + v2.getIndex());
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }
    }

    if (noSharedPackage_constrainedAs_WARNING_fromUsages) {
        if (!noSharedPackage_constrainedAs_ERROR_fromUsages)
            gDiagnostic.append(String.format("\n   OK: no shared package with WARNING usage constraints"));
    } else {
        int count = 0;
        for (Package p : sharedPackages_constrainedAs_WARNING_fromUsages.keySet()) {
            Set<Usage> usages = sharedPackages_constrainedAs_WARNING_fromUsages.get(p);
            if (usages.isEmpty())
                continue;
            count++;
            gMessages.append(String.format(
                    "\n shared package '%s' {URI=%s} has %d WARNING usage constraints from other shared packages",
                    p.getQualifiedName(), p.getURI(), usages.size()));

            for (Usage usage : usages) {
                if (usageConstraint2usingPackage.containsKey(usage)
                        && p.equals(usageConstraint2sharedPackage.get(usage))) {
                    Package source = usageConstraint2usingPackage.get(usage);
                    IProject ip1 = ProjectUtilities.getProject(source);
                    MDAbstractProject v1 = vertexMap.get(ip1);

                    IProject ip2 = ProjectUtilities.getProject(p);
                    MDAbstractProject v2 = vertexMap.get(ip2);

                    if (v1 != null && v2 != null) {
                        MDProjectUsageConstraint e = new MDProjectUsageConstraint(
                                MDProjectUsageConstraint.UsageConstraintLevel.WARNING, p.getQualifiedName());
                        e.setSource(v1);
                        e.setTarget(v2);
                        e.setIndex(e.getLabel() + ":" + v1.getIndex() + "=>" + v2.getIndex());
                        projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                    }
                }
            }
        }
        gDiagnostic.append(String.format("\n WARN: %d shared packages have WARNING usage constraints", count));
    }

    if (noSharedPackage_constrainedAs_ERROR_fromUsages) {
        if (!noSharedPackage_constrainedAs_WARNING_fromUsages)
            gDiagnostic.append(String.format("\n   OK: no shared package with ERROR usage constraints"));
    } else {
        int count = 0;
        for (Package p : sharedPackages_constrainedAs_ERROR_fromUsages.keySet()) {
            Set<Usage> usages = sharedPackages_constrainedAs_ERROR_fromUsages.get(p);
            if (usages.isEmpty())
                continue;
            count++;
            gMessages.append(String.format(
                    "\n shared package '%s' {URI=%s} has %d ERROR usage constraints from other shared packages",
                    p.getQualifiedName(), p.getURI(), usages.size()));

            for (Usage usage : usages) {
                if (usageConstraint2usingPackage.containsKey(usage)
                        && p.equals(usageConstraint2sharedPackage.get(usage))) {
                    Package source = usageConstraint2usingPackage.get(usage);
                    IProject ip1 = ProjectUtilities.getProject(source);
                    MDAbstractProject v1 = vertexMap.get(ip1);

                    IProject ip2 = ProjectUtilities.getProject(p);
                    MDAbstractProject v2 = vertexMap.get(ip2);

                    if (v1 != null && v2 != null) {
                        MDProjectUsageConstraint e = new MDProjectUsageConstraint(
                                MDProjectUsageConstraint.UsageConstraintLevel.ERROR, p.getQualifiedName());
                        e.setSource(v1);
                        e.setTarget(v2);
                        e.setIndex(e.getLabel() + ":" + v1.getIndex() + "=>" + v2.getIndex());
                        projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                    }
                }
            }
        }
        gDiagnostic.append(String.format("\nERROR: %d shared packages have ERROR usage constraints", count));
    }

    boolean showClassificationConstraints = plugin.options.getShowClassificationConstraintsAsEdgesProperty();

    if (!sharedPackages_classified_DEPRECATED.isEmpty()) {
        if (no_DEPRECATED_WARNING_constraintViolations && no_DEPRECATED_ERROR_constraintViolations)
            gDiagnostic.append(String.format("\n   OK: all DEPRECATED shared packages are used consistently"));

        if (no_DEPRECATED_WARNING_constraintViolations) {
            if (!no_DEPRECATED_ERROR_constraintViolations)
                gDiagnostic.append(
                        String.format("\n   OK: no DEPRECATED shared packages have WARNING usage constraints"));
        } else {
            showClassificationConstraints = true;
            gDiagnostic.append(
                    String.format("\n WARN: %d DEPRECATED shared packages have WARNING usage constraints",
                            sharedPackages_classified_DEPRECATED.size()));
            for (Package p : sharedPackages_classified_DEPRECATED) {
                gMessages.append(String.format(
                        "\n shared package '%s' {URI=%s} is DEPRECATED with some usage constraint classified as WARNING",
                        p.getQualifiedName(), p.getURI()));
            }
        }

        if (no_DEPRECATED_ERROR_constraintViolations) {
            if (!no_DEPRECATED_WARNING_constraintViolations)
                gDiagnostic.append(
                        String.format("\n   OK: no DEPRECATED shared packages have ERROR usage constraints"));
        } else {
            showClassificationConstraints = true;
            gDiagnostic
                    .append(String.format("\nERROR: %d DEPRECATED shared packages have ERROR usage constraints",
                            sharedPackages_classified_DEPRECATED.size()));
            for (Package p : sharedPackages_classified_DEPRECATED) {
                gMessages.append(String.format(
                        "\n shared package '%s' {URI=%s} is DEPRECATED with some usage constraint classified as ERROR",
                        p.getQualifiedName(), p.getURI()));
            }
        }
    }

    if (!sharedPackages_classified_INCUBATOR.isEmpty()) {
        if (no_INCUBATOR_WARNING_constraintViolations) {
            if (!no_INCUBATOR_ERROR_constraintViolations)
                gDiagnostic.append(
                        String.format("\n   OK: no INCUBATOR shared packages have WARNING usage constraints"));
        } else {
            showClassificationConstraints = true;
            gDiagnostic.append(
                    String.format("\n WARN: %d INCUBATOR shared packages have WARNING usage constraints",
                            sharedPackages_classified_INCUBATOR.size()));
            for (Package p : sharedPackages_classified_INCUBATOR) {
                gMessages.append(String.format(
                        "\n shared package '%s' {URI=%s} is INCUBATOR with some usage constraint classified as WARNING",
                        p.getQualifiedName(), p.getURI()));
            }
        }

        if (no_INCUBATOR_ERROR_constraintViolations) {
            if (!no_INCUBATOR_WARNING_constraintViolations)
                gDiagnostic.append(
                        String.format("\n   OK: no INCUBATOR shared packages have ERROR usage constraints"));
        } else {
            showClassificationConstraints = true;
            gDiagnostic
                    .append(String.format("\nERROR: %d INCUBATOR shared packages have ERROR usage constraints",
                            sharedPackages_classified_INCUBATOR.size()));
            for (Package p : sharedPackages_classified_INCUBATOR) {
                gMessages.append(String.format(
                        "\n shared package '%s' {URI=%s} is INCUBATOR with some usage constraint classified as ERROR",
                        p.getQualifiedName(), p.getURI()));
            }
        }
    }

    if (!sharedPackages_classified_RECOMMENDED.isEmpty()) {
        if (no_RECOMMENDED_WARNING_constraintViolations) {
            if (!no_RECOMMENDED_ERROR_constraintViolations)
                gDiagnostic.append(String
                        .format("\n   OK: no RECOMMENDED shared packages have WARNING usage constraints"));
        } else {
            showClassificationConstraints = true;
            gDiagnostic.append(
                    String.format("\n WARN: %d RECOMMENDED shared packages have WARNING usage constraints",
                            sharedPackages_classified_RECOMMENDED.size()));
            for (Package p : sharedPackages_classified_RECOMMENDED) {
                gMessages.append(String.format(
                        "\n shared package '%s' {URI=%s} is RECOMMENDED with some usage constraint classified as WARNING",
                        p.getQualifiedName(), p.getURI()));
            }
        }

        if (no_RECOMMENDED_ERROR_constraintViolations) {
            if (!no_RECOMMENDED_WARNING_constraintViolations)
                gDiagnostic.append(
                        String.format("\n   OK: no RECOMMENDED shared packages have ERROR usage constraints"));
        } else {
            showClassificationConstraints = true;
            gDiagnostic.append(
                    String.format("\nERROR: %d RECOMMENDED shared packages have ERROR usage constraints",
                            sharedPackages_classified_RECOMMENDED.size()));
            for (Package p : sharedPackages_classified_RECOMMENDED) {
                gMessages.append(String.format(
                        "\n shared package '%s' {URI=%s} is RECOMMENDED with some usage constraint classified as ERROR",
                        p.getQualifiedName(), p.getURI()));
            }
        }
    }

    if (moduleOrProjectWithInconsistentlyClassifiedSharedPackages.isEmpty()) {
        gDiagnostic.append(
                String.format("\n   OK: all modules & project have consistent shared package classifications"));
    } else {
        showClassificationConstraints = true;
        gDiagnostic.append(
                String.format("\nERROR: %d modules/project with shared packages inconsistently classified",
                        moduleOrProjectWithInconsistentlyClassifiedSharedPackages.size()));
        for (MDAbstractProject v : moduleOrProjectWithInconsistentlyClassifiedSharedPackages) {
            gMessages.append(String.format(
                    "\n module/project '%s' has shared packages inconsistently classified", v.getName()));
        }
    }

    // TODO: this logic needs to be optimized...

    if (showClassificationConstraints) {
        for (Package p1 : sharedPackages_constraining_DEPRECATED_packages_as_OK) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_DEPRECATED) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.OK,
                            MDProjectClassificationConstraint.ClassificationLevel.DEPRECATED,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    e.setIndex(e.getLabel() + ":" + v1.getIndex() + "=>" + v2.getIndex());
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }

        for (Package p1 : sharedPackages_constraining_DEPRECATED_packages_as_WARNING) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_DEPRECATED) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.WARNING,
                            MDProjectClassificationConstraint.ClassificationLevel.DEPRECATED,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    e.setIndex(e.getLabel() + ":" + v1.getIndex() + "=>" + v2.getIndex());
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }

        for (Package p1 : sharedPackages_constraining_DEPRECATED_packages_as_ERROR) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_DEPRECATED) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.ERROR,
                            MDProjectClassificationConstraint.ClassificationLevel.DEPRECATED,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }

        for (Package p1 : sharedPackages_constraining_INCUBATOR_packages_as_OK) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_INCUBATOR) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.OK,
                            MDProjectClassificationConstraint.ClassificationLevel.INCUBATOR,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }

        for (Package p1 : sharedPackages_constraining_INCUBATOR_packages_as_WARNING) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_INCUBATOR) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.WARNING,
                            MDProjectClassificationConstraint.ClassificationLevel.INCUBATOR,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }

        for (Package p1 : sharedPackages_constraining_INCUBATOR_packages_as_ERROR) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_INCUBATOR) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.ERROR,
                            MDProjectClassificationConstraint.ClassificationLevel.INCUBATOR,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }

        for (Package p1 : sharedPackages_constraining_RECOMMENDED_packages_as_OK) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_RECOMMENDED) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.OK,
                            MDProjectClassificationConstraint.ClassificationLevel.RECOMMENDED,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }

        for (Package p1 : sharedPackages_constraining_RECOMMENDED_packages_as_WARNING) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_RECOMMENDED) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.WARNING,
                            MDProjectClassificationConstraint.ClassificationLevel.RECOMMENDED,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }

        for (Package p1 : sharedPackages_constraining_RECOMMENDED_packages_as_ERROR) {
            IProject ip1 = ProjectUtilities.getProject(p1);
            MDAbstractProject v1 = vertexMap.get(ip1);

            for (Package p2 : sharedPackages_classified_RECOMMENDED) {
                IProject ip2 = ProjectUtilities.getProject(p2);
                MDAbstractProject v2 = vertexMap.get(ip2);

                if (v1 != null && v2 != null) {
                    MDProjectClassificationConstraint e = new MDProjectClassificationConstraint(
                            MDProjectClassificationConstraint.UsageConstraintLevel.ERROR,
                            MDProjectClassificationConstraint.ClassificationLevel.RECOMMENDED,
                            p2.getQualifiedName());
                    e.setSource(v1);
                    e.setTarget(v2);
                    projectUsageDirectedMultigraph.addEdge(v1, v2, e);
                }
            }
        }
    }

    notifySSCAE = createSerialization(allSortedProjects, notifySSCAE);

    if (notifySSCAE) {
        pluginLog.error(String.format(
                "*** Notify SECAE ***\n====Diagnostic:\n%s\n====\n\n====Serialization:\n%s\n====\n\n====Messages:\n%s\n====\n",
                gDiagnostic.toString(), gSerialization.toString(), gMessages.toString()));
    }

    gSignature.append(gSerialization.toString());
    gSignature.append(gMessages.toString());

    final DOTExporterWithLegend<MDAbstractProject, MDAbstractProjectUsage> dotExporter = new DOTExporterWithLegend<MDAbstractProject, MDAbstractProjectUsage>(
            VERTEX_ID_PROVIDER, VERTEX_LABEL_PROVIDER, EDGE_LABEL_PROVIDER, VERTEX_ATTRIBUTE_PROVIDER,
            EDGE_ATTRIBUTE_PROVIDER) {
        @Override
        protected void legend(PrintWriter out) {
            writeProjectUsageGraphLegend(out);
        }
    };

    dotExporter.export(gDOT, projectUsageDirectedMultigraph);

    final DOTExporterWithLegend<MDAbstractProject, MDAbstractProjectUsage> teamworkDotExporter = new DOTExporterWithLegend<MDAbstractProject, MDAbstractProjectUsage>(
            VERTEX_ID_PROVIDER, VERTEX_LABEL_PROVIDER, EDGE_LABEL_PROVIDER, VERTEX_ATTRIBUTE_PROVIDER,
            EDGE_ATTRIBUTE_PROVIDER) {
        @Override
        protected void legend(PrintWriter out) {
            writeProjectTeamworkUsageGraphLegend(out);
        }
    };

    teamworkDotExporter.export(gDOTteamworkOnly, new MaskSubgraph<MDAbstractProject, MDAbstractProjectUsage>(
            projectUsageDirectedMultigraph, new MaskFunctor<MDAbstractProject, MDAbstractProjectUsage>() {

                @Override
                public boolean isEdgeMasked(MDAbstractProjectUsage e) {
                    return (e instanceof MDLocalProjectUsage);
                }

                @Override
                public boolean isVertexMasked(MDAbstractProject v) {
                    return (v instanceof MDLocalProject);
                }

            }));

    if (plugin.isShowAdvancedInformationProperty()) {
        for (MDAbstractProject v : projectUsageDirectedMultigraph.vertexSet()) {
            gSerialization.append(String.format("\nV: %s (isNew=%b)", v, v.isNew()));
        }

        for (MDAbstractProjectUsage e : projectUsageDirectedMultigraph.edgeSet()) {
            MDAbstractProject eSource = projectUsageDirectedMultigraph.getEdgeSource(e);
            MDAbstractProject eTarget = projectUsageDirectedMultigraph.getEdgeTarget(e);
            gSerialization.append(String.format("\nE: %s %s", e, e.getMDFlags()));
        }
    }
}

From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java

private void removeFieldFromReportChecks(ReportFieldInfo reportField, HttpServletRequest request)
        throws CantDoThatException, CodingErrorException, ObjectNotFoundException {
    // check the field isn't used in one of the report's own charts
    for (ChartInfo chart : reportField.getParentReport().getSavedCharts()) {
        Set<ChartAggregateInfo> aggFns = chart.getAggregateFunctions();
        for (ChartAggregateInfo aggFn : aggFns) {
            ReportFieldInfo aggReportField = aggFn.getReportField();
            if (aggReportField.equals(reportField)) {
                throw new CantDoThatException(
                        "Please remove the chart calculation " + aggFn + " before removing the report field");
            }/* ww w  . j  a  va  2  s.co m*/
            ReportFieldInfo secondaryAggReportField = aggFn.getSecondaryReportField();
            if (secondaryAggReportField != null) {
                if (secondaryAggReportField.equals(reportField)) {
                    throw new CantDoThatException("Please remove the report summary calculation " + aggFn
                            + " before removing the report field");
                }
            }
        }
        for (ChartGroupingInfo grouping : chart.getGroupings()) {
            if (grouping.getGroupingReportField().equals(reportField)) {
                throw new CantDoThatException("Please remove the chart grouping on " + reportField
                        + " before removing the report field");
            }
        }
        if (reportField.equals(chart.getFilterReportField())) {
            throw new CantDoThatException(
                    "Please remove the chart filter on " + reportField + " before removing the report field");
        }
    }
    BaseReportInfo thisReport = reportField.getParentReport();
    // check the field isn't referenced from any other reports
    SortedSet<BaseReportInfo> reportsUsedIn = new TreeSet<BaseReportInfo>();
    CompanyInfo company = this.authManager.getCompanyForLoggedInUser(request);
    Set<TableInfo> allTables = company.getTables();
    for (TableInfo testTable : allTables) {
        for (BaseReportInfo testReport : testTable.getReports()) {
            if (testReport.equals(testReport.getParentTable().getDefaultReport())) {
                continue;
            }
            for (ReportFieldInfo testReportField : testReport.getReportFields()) {
                if (testReportField.isFieldFromReport()) {
                    BaseReportInfo reportFieldIsFrom = testReportField.getReportFieldIsFrom();
                    if (reportFieldIsFrom.equals(reportField.getParentReport())
                            && testReportField.getBaseField().equals(reportField.getBaseField())) {
                        if (!((reportField instanceof ReportCalcFieldInfo)
                                && (reportField.equals(testReportField)))) {
                            reportsUsedIn.add(testReportField.getParentReport());
                        }
                    }
                }
                if (testReportField instanceof ReportCalcFieldInfo) {
                    String calcSQL = ((ReportCalcFieldInfo) testReportField).getCalculationSQL(true);
                    if (calcSQL.contains(reportField.getParentReport().getInternalReportName() + "."
                            + reportField.getInternalFieldName())) {
                        if (!testReportField.equals(reportField)) {
                            reportsUsedIn.add(testReport);
                        }
                    }
                }
            }
            if (testReport instanceof SimpleReportInfo) {
                SimpleReportInfo simpleTestReport = (SimpleReportInfo) testReport;
                for (JoinClauseInfo join : simpleTestReport.getJoins()) {
                    if (!join.isLeftPartTable()) {
                        ReportFieldInfo joinReportField = join.getLeftReportField();
                        if (joinReportField.equals(reportField)) {
                            reportsUsedIn.add(testReport);
                        }
                    }
                    if (!join.isRightPartTable()) {
                        ReportFieldInfo joinReportField = join.getRightReportField();
                        if (joinReportField.equals(reportField)) {
                            reportsUsedIn.add(testReport);
                        }
                    }
                }
            }
        }
    }
    // check field isn't referenced from any calcs in the same report
    for (ReportFieldInfo testReportField : reportField.getParentReport().getReportFields()) {
        if (testReportField instanceof ReportCalcFieldInfo) {
            if (reportField.isFieldFromReport()) {
                // Field references calculation in another report, that's ok
                continue;
            }
            ReportCalcFieldInfo testCalc = (ReportCalcFieldInfo) testReportField;
            String calcSQL = testCalc.getCalculationSQL(false);
            if (calcSQL.contains(reportField.getInternalFieldName())) {
                throw new CantDoThatException(
                        "The report field " + reportField + " is referenced by the calculation " + testCalc
                                + ". Please remove or update this calculation before removing " + reportField);
            }
        }
    }
    if (reportsUsedIn.size() > 0) {
        String errorMessage = "The report field " + reportField + " is used in the following reports: ";
        for (BaseReportInfo report : reportsUsedIn) {
            ModuleInfo module = report.getModule();
            if (module == null) {
                errorMessage = errorMessage + report.getParentTable() + "." + report + ", ";
            } else {
                errorMessage = errorMessage + module + " > " + report + ", ";
            }
        }
        errorMessage = errorMessage.substring(0, errorMessage.length() - 2);
        errorMessage += ". Please remove all references in these reports before removing it from the "
                + reportField.getParentReport() + " report";
        throw new CantDoThatException(errorMessage);
    }
}

From source file:com.android.mms.transaction.MessagingNotification.java

private static final void addMmsNotificationInfos(Context context, Set<Long> threads,
        SortedSet<NotificationInfo> notificationSet) {
    ContentResolver resolver = context.getContentResolver();

    // This query looks like this when logged:
    // I/Database(  147): elapsedTime4Sql|/data/data/com.android.providers.telephony/databases/
    // mmssms.db|0.362 ms|SELECT thread_id, date, _id, sub, sub_cs FROM pdu WHERE ((msg_box=1
    // AND seen=0 AND (m_type=130 OR m_type=132))) ORDER BY date desc

    Cursor cursor = SqliteWrapper.query(context, resolver, Mms.CONTENT_URI, MMS_STATUS_PROJECTION,
            NEW_INCOMING_MM_CONSTRAINT, null, Mms.DATE + " desc");

    if (cursor == null) {
        return;//from ww w.  j a  v  a 2  s  . co  m
    }

    try {
        while (cursor.moveToNext()) {

            long msgId = cursor.getLong(COLUMN_MMS_ID);
            Uri msgUri = Mms.CONTENT_URI.buildUpon().appendPath(Long.toString(msgId)).build();
            String address = AddressUtils.getFrom(context, msgUri);

            Contact contact = Contact.get(address, false);
            if (contact.getSendToVoicemail()) {
                // don't notify, skip this one
                continue;
            }

            String subject = getMmsSubject(cursor.getString(COLUMN_MMS_SUBJECT),
                    cursor.getInt(COLUMN_MMS_SUBJECT_CS));
            subject = MessageUtils.cleanseMmsSubject(context, subject);

            long threadId = cursor.getLong(COLUMN_MMS_THREAD_ID);
            long timeMillis = cursor.getLong(COLUMN_MMS_DATE) * 1000;
            int subId = cursor.getInt(COLUMN_MMS_SUB_ID);

            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
                Log.d(TAG, "addMmsNotificationInfos: count=" + cursor.getCount() + ", addr = " + address
                        + ", thread_id=" + threadId);
            }

            // Extract the message and/or an attached picture from the first slide
            Bitmap attachedPicture = null;
            String messageBody = null;
            int attachmentType = WorkingMessage.TEXT;
            try {
                GenericPdu pdu = sPduPersister.load(msgUri);
                if (pdu != null && pdu instanceof MultimediaMessagePdu) {
                    SlideshowModel slideshow = SlideshowModel.createFromPduBody(context,
                            ((MultimediaMessagePdu) pdu).getBody());
                    attachmentType = getAttachmentType(slideshow);
                    SlideModel firstSlide = slideshow.get(0);
                    if (firstSlide != null) {
                        if (firstSlide.hasImage()) {
                            int maxDim = dp2Pixels(MAX_BITMAP_DIMEN_DP);
                            attachedPicture = firstSlide.getImage().getBitmap(maxDim, maxDim);
                        }
                        if (firstSlide.hasText()) {
                            messageBody = firstSlide.getText().getText();
                        }
                    }
                }
            } catch (final MmsException e) {
                Log.e(TAG, "MmsException loading uri: " + msgUri, e);
                continue; // skip this bad boy -- don't generate an empty notification
            }

            NotificationInfo info = getNewMessageNotificationInfo(context, false /* isSms */, address,
                    messageBody, subject, threadId, subId, timeMillis, attachedPicture, contact,
                    attachmentType);
            if (MessageUtils.isMailboxMode()) {
                info.mClickIntent.setData(msgUri);
            }
            notificationSet.add(info);

            threads.add(threadId);
        }
    } finally {
        cursor.close();
    }
}

From source file:com.gtwm.pb.model.manageData.DataManagement.java

public SortedSet<CommentInfo> getComments(BaseField field, int rowId) throws SQLException, CantDoThatException {
    SortedSet<CommentInfo> comments = new TreeSet<CommentInfo>();
    Boolean hasComments = field.hasComments();
    if (hasComments != null) {
        if (hasComments.equals(false)) {
            return comments;
        }// w  w w .j a  va  2  s . co  m
    }
    String sqlCode = "SELECT created, author, text FROM dbint_comments WHERE internalfieldname=? AND rowid=? order by created desc limit 10";
    Connection conn = null;
    try {
        conn = this.dataSource.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement statement = conn.prepareStatement(sqlCode);
        String internalFieldName = field.getInternalFieldName();
        statement.setString(1, internalFieldName);
        statement.setInt(2, rowId);
        ResultSet results = statement.executeQuery();
        while (results.next()) {
            Timestamp createdTimestamp = results.getTimestamp(1);
            Calendar created = Calendar.getInstance();
            created.setTimeInMillis(createdTimestamp.getTime());
            String author = results.getString(2);
            String comment = results.getString(3);
            comments.add(new Comment(internalFieldName, rowId, author, created, comment));
        }
        results.close();
        statement.close();
        if (comments.size() > 0) {
            field.setHasComments(true);
        } else if (hasComments == null) {
            // We've seen there are no comments for this particular record
            // but we don't know if there are any for the field in other
            // records. Check.
            sqlCode = "SELECT count(*) from dbint_comments WHERE internalfieldname=?";
            statement = conn.prepareStatement(sqlCode);
            statement.setString(1, internalFieldName);
            results = statement.executeQuery();
            if (results.next()) {
                int numComments = results.getInt(1);
                if (numComments > 0) {
                    field.setHasComments(true);
                } else {
                    // Another check in case another thread e.g. running
                    // addComment has set this to true.
                    // We don't want to overwrite that
                    // TODO: Really, this should be atomic but it takes such
                    // a small amount of time compared to the SQL it's
                    // probably fine
                    if (field.hasComments() == null) {
                        field.setHasComments(false);
                    }
                }
            } else {
                logger.error("Unable to see if comments exist with query " + statement);
            }
            results.close();
            statement.close();
        }
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
    return comments;
}

From source file:net.sourceforge.fenixedu.domain.Person.java

public SortedSet<String> getOrganizationalUnitsPresentation() {
    final SortedSet<String> organizationalUnits = new TreeSet<String>();
    for (final Accountability accountability : getParentsSet()) {
        if (isOrganizationalUnitsForPresentation(accountability)) {
            final Party party = accountability.getParentParty();
            organizationalUnits.add(party.getName());
        }//from   w  w w.j a v  a2 s . c om
    }
    if (getStudent() != null) {
        for (final Registration registration : getStudent().getRegistrationsSet()) {
            if (registration.isActive()) {
                final DegreeCurricularPlan degreeCurricularPlan = registration.getLastDegreeCurricularPlan();
                if (degreeCurricularPlan != null) {
                    final Degree degree = degreeCurricularPlan.getDegree();
                    organizationalUnits.add(degree.getPresentationName());
                }
            }
        }
    }
    return organizationalUnits;
}

From source file:org.alfresco.repo.domain.node.AbstractNodeDAOImpl.java

/**
 * Bulk-fetch the nodes for a given store.  All nodes passed in are fetched.
 *//* ww  w .  j  a  v a  2s  . com*/
private void cacheNodesNoBatch(List<Node> nodes) {
    // Get the nodes
    SortedSet<Long> aspectNodeIds = new TreeSet<Long>();
    SortedSet<Long> propertiesNodeIds = new TreeSet<Long>();
    Map<Long, NodeVersionKey> nodeVersionKeysFromCache = new HashMap<Long, NodeVersionKey>(nodes.size() * 2); // Keep for quick lookup
    for (Node node : nodes) {
        Long nodeId = node.getId();
        NodeVersionKey nodeVersionKey = node.getNodeVersionKey();
        node.lock(); // Prevent unexpected edits of values going into the cache
        nodesCache.setValue(nodeId, node);
        if (propertiesCache.getValue(nodeVersionKey) == null) {
            propertiesNodeIds.add(nodeId);
        }
        if (aspectsCache.getValue(nodeVersionKey) == null) {
            aspectNodeIds.add(nodeId);
        }
        nodeVersionKeysFromCache.put(nodeId, nodeVersionKey);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Pre-loaded " + propertiesNodeIds.size() + " properties");
        logger.debug("Pre-loaded " + propertiesNodeIds.size() + " aspects");
    }

    Map<NodeVersionKey, Set<QName>> nodeAspects = selectNodeAspects(aspectNodeIds);
    for (Map.Entry<NodeVersionKey, Set<QName>> entry : nodeAspects.entrySet()) {
        NodeVersionKey nodeVersionKeyFromDb = entry.getKey();
        Long nodeId = nodeVersionKeyFromDb.getNodeId();
        Set<QName> qnames = entry.getValue();
        setNodeAspectsCached(nodeId, qnames);
        aspectNodeIds.remove(nodeId);
    }
    // Cache the absence of aspects too!
    for (Long nodeId : aspectNodeIds) {
        setNodeAspectsCached(nodeId, Collections.<QName>emptySet());
    }

    // First ensure all content data are pre-cached, so we don't have to load them individually when converting properties
    contentDataDAO.cacheContentDataForNodes(propertiesNodeIds);

    // Now bulk load the properties
    Map<NodeVersionKey, Map<NodePropertyKey, NodePropertyValue>> propsByNodeId = selectNodeProperties(
            propertiesNodeIds);
    for (Map.Entry<NodeVersionKey, Map<NodePropertyKey, NodePropertyValue>> entry : propsByNodeId.entrySet()) {
        Long nodeId = entry.getKey().getNodeId();
        Map<NodePropertyKey, NodePropertyValue> propertyValues = entry.getValue();
        Map<QName, Serializable> props = nodePropertyHelper.convertToPublicProperties(propertyValues);
        setNodePropertiesCached(nodeId, props);
    }
}

From source file:net.sourceforge.fenixedu.domain.Person.java

public SortedSet<StudentCurricularPlan> getActiveStudentCurricularPlansSortedByDegreeTypeAndDegreeName() {
    final SortedSet<StudentCurricularPlan> studentCurricularPlans = new TreeSet<StudentCurricularPlan>(
            StudentCurricularPlan.STUDENT_CURRICULAR_PLAN_COMPARATOR_BY_DEGREE_TYPE_AND_DEGREE_NAME);
    for (final Registration registration : getStudentsSet()) {
        final StudentCurricularPlan studentCurricularPlan = registration.getActiveStudentCurricularPlan();
        if (studentCurricularPlan != null) {
            studentCurricularPlans.add(studentCurricularPlan);
        }/*from   w  ww. j  ava 2  s.c o  m*/
    }
    return studentCurricularPlans;
}

From source file:net.sourceforge.fenixedu.domain.Person.java

public SortedSet<StudentCurricularPlan> getCompletedStudentCurricularPlansSortedByDegreeTypeAndDegreeName() {
    final SortedSet<StudentCurricularPlan> studentCurricularPlans = new TreeSet<StudentCurricularPlan>(
            StudentCurricularPlan.STUDENT_CURRICULAR_PLAN_COMPARATOR_BY_DEGREE_TYPE_AND_DEGREE_NAME);

    for (final Registration registration : getStudentsSet()) {
        if (registration.isConcluded()) {
            final StudentCurricularPlan lastStudent = registration.getLastStudentCurricularPlan();
            if (lastStudent != null) {
                studentCurricularPlans.add(lastStudent);
            }//  ww w  .  j a v a 2 s .co m
        }
    }
    return studentCurricularPlans;
}

From source file:net.sourceforge.fenixedu.domain.student.Registration.java

public Grade findGradeForCurricularCourse(final CurricularCourse curricularCourse) {
    final SortedSet<Enrolment> enrolments = new TreeSet<Enrolment>(
            Enrolment.REVERSE_COMPARATOR_BY_EXECUTION_PERIOD_AND_ID);
    for (final StudentCurricularPlan studentCurricularPlan : getStudentCurricularPlansSet()) {
        for (final Enrolment enrolment : studentCurricularPlan.getEnrolmentsSet()) {
            final CurricularCourse enrolmentCurricularCourse = enrolment.getCurricularCourse();
            if (enrolmentCurricularCourse == curricularCourse
                    || (enrolmentCurricularCourse.getCompetenceCourse() != null && enrolmentCurricularCourse
                            .getCompetenceCourse() == curricularCourse.getCompetenceCourse())
                    || hasGlobalEquivalence(curricularCourse, enrolmentCurricularCourse)) {
                enrolments.add(enrolment);
            }//  w w w .  j  a  v a  2  s.  c  om
        }
    }

    for (final Enrolment enrolment : enrolments) {
        final EnrolmentEvaluation enrolmentEvaluation = enrolment.getLatestEnrolmentEvaluation();
        if (enrolmentEvaluation != null && enrolmentEvaluation.isApproved()) {
            return enrolmentEvaluation.getGrade();
        }
    }

    return null;
}