Search in sources :

Example 76 with SortedMap

use of java.util.SortedMap in project gerrit by GerritCodeReview.

the class ListProjects method display.

public SortedMap<String, ProjectInfo> display(@Nullable OutputStream displayOutputStream) throws BadRequestException, PermissionBackendException {
    if (groupUuid != null) {
        try {
            if (!groupControlFactory.controlFor(groupUuid).isVisible()) {
                return Collections.emptySortedMap();
            }
        } catch (NoSuchGroupException ex) {
            return Collections.emptySortedMap();
        }
    }
    PrintWriter stdout = null;
    if (displayOutputStream != null) {
        stdout = new PrintWriter(new BufferedWriter(new OutputStreamWriter(displayOutputStream, UTF_8)));
    }
    if (type == FilterType.PARENT_CANDIDATES) {
        // Historically, PARENT_CANDIDATES implied showDescription.
        showDescription = true;
    }
    int foundIndex = 0;
    int found = 0;
    TreeMap<String, ProjectInfo> output = new TreeMap<>();
    Map<String, String> hiddenNames = new HashMap<>();
    Map<Project.NameKey, Boolean> accessibleParents = new HashMap<>();
    PermissionBackend.WithUser perm = permissionBackend.user(currentUser);
    final TreeMap<Project.NameKey, ProjectNode> treeMap = new TreeMap<>();
    try {
        for (final Project.NameKey projectName : filter(perm)) {
            final ProjectState e = projectCache.get(projectName);
            if (e == null || (!all && e.getProject().getState() == HIDDEN)) {
                // If all wasn't selected, and its HIDDEN, pretend its not present.
                continue;
            }
            final ProjectControl pctl = e.controlFor(currentUser);
            if (groupUuid != null && !pctl.getLocalGroups().contains(GroupReference.forGroup(groupsCollection.parseId(groupUuid.get())))) {
                continue;
            }
            ProjectInfo info = new ProjectInfo();
            if (showTree && !format.isJson()) {
                treeMap.put(projectName, projectNodeFactory.create(pctl.getProject(), true));
                continue;
            }
            info.name = projectName.get();
            if (showTree && format.isJson()) {
                ProjectState parent = Iterables.getFirst(e.parents(), null);
                if (parent != null) {
                    if (isParentAccessible(accessibleParents, perm, parent)) {
                        info.parent = parent.getProject().getName();
                    } else {
                        info.parent = hiddenNames.get(parent.getProject().getName());
                        if (info.parent == null) {
                            info.parent = "?-" + (hiddenNames.size() + 1);
                            hiddenNames.put(parent.getProject().getName(), info.parent);
                        }
                    }
                }
            }
            if (showDescription) {
                info.description = Strings.emptyToNull(e.getProject().getDescription());
            }
            info.state = e.getProject().getState();
            try {
                if (!showBranch.isEmpty()) {
                    try (Repository git = repoManager.openRepository(projectName)) {
                        if (!type.matches(git)) {
                            continue;
                        }
                        List<Ref> refs = getBranchRefs(projectName, pctl);
                        if (!hasValidRef(refs)) {
                            continue;
                        }
                        for (int i = 0; i < showBranch.size(); i++) {
                            Ref ref = refs.get(i);
                            if (ref != null && ref.getObjectId() != null) {
                                if (info.branches == null) {
                                    info.branches = new LinkedHashMap<>();
                                }
                                info.branches.put(showBranch.get(i), ref.getObjectId().name());
                            }
                        }
                    }
                } else if (!showTree && type.useMatch()) {
                    try (Repository git = repoManager.openRepository(projectName)) {
                        if (!type.matches(git)) {
                            continue;
                        }
                    }
                }
            } catch (RepositoryNotFoundException err) {
                // If the Git repository is gone, the project doesn't actually exist anymore.
                continue;
            } catch (IOException err) {
                log.warn("Unexpected error reading " + projectName, err);
                continue;
            }
            if (type != FilterType.PARENT_CANDIDATES) {
                List<WebLinkInfo> links = webLinks.getProjectLinks(projectName.get());
                info.webLinks = links.isEmpty() ? null : links;
            }
            if (foundIndex++ < start) {
                continue;
            }
            if (limit > 0 && ++found > limit) {
                break;
            }
            if (stdout == null || format.isJson()) {
                output.put(info.name, info);
                continue;
            }
            if (!showBranch.isEmpty()) {
                for (String name : showBranch) {
                    String ref = info.branches != null ? info.branches.get(name) : null;
                    if (ref == null) {
                        // Print stub (forty '-' symbols)
                        ref = "----------------------------------------";
                    }
                    stdout.print(ref);
                    stdout.print(' ');
                }
            }
            stdout.print(info.name);
            if (info.description != null) {
                // We still want to list every project as one-liners, hence escaping \n.
                stdout.print(" - " + StringUtil.escapeString(info.description));
            }
            stdout.print('\n');
        }
        for (ProjectInfo info : output.values()) {
            info.id = Url.encode(info.name);
            info.name = null;
        }
        if (stdout == null) {
            return output;
        } else if (format.isJson()) {
            format.newGson().toJson(output, new TypeToken<Map<String, ProjectInfo>>() {
            }.getType(), stdout);
            stdout.print('\n');
        } else if (showTree && treeMap.size() > 0) {
            printProjectTree(stdout, treeMap);
        }
        return null;
    } finally {
        if (stdout != null) {
            stdout.flush();
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) NoSuchGroupException(com.google.gerrit.common.errors.NoSuchGroupException) BufferedWriter(java.io.BufferedWriter) ProjectInfo(com.google.gerrit.extensions.common.ProjectInfo) PrintWriter(java.io.PrintWriter) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) TreeMap(java.util.TreeMap) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) WebLinkInfo(com.google.gerrit.extensions.common.WebLinkInfo) OutputStreamWriter(java.io.OutputStreamWriter) Map(java.util.Map) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 77 with SortedMap

use of java.util.SortedMap in project uPortal by Jasig.

the class SearchPortletController method getCleanedAndSortedMapResults.

/**
     * Return the search results in a sorted map based on priority of the search result type
     *
     * @param resultsMap Search results map
     * @return Sorted map of search results ordered on search result type priority
     */
private SortedMap<Integer, List<AutocompleteResultsModel>> getCleanedAndSortedMapResults(ConcurrentMap<String, List<Tuple<SearchResult, String>>> resultsMap, int maxTextLength) {
    SortedMap<Integer, List<AutocompleteResultsModel>> prioritizedResultsMap = createAutocompletePriorityMap();
    // Put the results into the map of <priority,list>
    for (Map.Entry<String, List<Tuple<SearchResult, String>>> entry : resultsMap.entrySet()) {
        for (Tuple<SearchResult, String> tupleSearchResult : entry.getValue()) {
            SearchResult searchResult = tupleSearchResult.getFirst();
            List<String> resultTypes = searchResult.getType();
            // If the search result doesn't have a type defined, use the undefined result type.
            if (resultTypes.size() == 0) {
                resultTypes = UNDEFINED_SEARCH_RESULT_TYPE;
            }
            for (String category : resultTypes) {
                // Exclude the result if it is a result type that's in the ignore list.
                if (!autocompleteIgnoreResultTypes.contains(category)) {
                    int priority = calculatePriorityFromCategory(category);
                    AutocompleteResultsModel result = new AutocompleteResultsModel(cleanAndTrimString(searchResult.getTitle(), maxTextLength), cleanAndTrimString(searchResult.getSummary(), maxTextLength), tupleSearchResult.getSecond(), category);
                    prioritizedResultsMap.get(priority).add(result);
                }
            }
        }
    }
    return prioritizedResultsMap;
}
Also used : List(java.util.List) ArrayList(java.util.ArrayList) SearchResult(org.apereo.portal.search.SearchResult) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap)

Example 78 with SortedMap

use of java.util.SortedMap in project intellij-plugins by JetBrains.

the class DartCoverageRunner method doLoadCoverageData.

@Nullable
private static ProjectData doLoadCoverageData(@NotNull final File sessionDataFile, @NotNull final DartCoverageSuite coverageSuite) {
    final ProcessHandler coverageProcess = coverageSuite.getCoverageProcess();
    // coverageProcess == null means that we are switching to data gathered earlier
    if (coverageProcess != null) {
        for (int i = 0; i < 100; ++i) {
            ProgressManager.checkCanceled();
            if (coverageProcess.waitFor(100)) {
                break;
            }
        }
        if (!coverageProcess.isProcessTerminated()) {
            coverageProcess.destroyProcess();
            return null;
        }
    }
    final Project project = coverageSuite.getProject();
    final String contextFilePath = coverageSuite.getContextFilePath();
    if (project == null || contextFilePath == null) {
        return null;
    }
    final String contextId = DartAnalysisServerService.getInstance(project).execution_createContext(contextFilePath);
    if (contextId == null) {
        return null;
    }
    final ProjectData projectData = new ProjectData();
    try {
        DartCoverageData data = new Gson().fromJson(new BufferedReader(new FileReader(sessionDataFile)), DartCoverageData.class);
        if (data == null) {
            LOG.warn("Coverage file does not contain valid data.");
            return null;
        }
        for (Map.Entry<String, SortedMap<Integer, Integer>> entry : data.getMergedDartFileCoverageData().entrySet()) {
            ProgressManager.checkCanceled();
            String filePath = getFileForUri(project, contextId, entry.getKey());
            if (filePath == null) {
                // File is not found.
                continue;
            }
            SortedMap<Integer, Integer> lineHits = entry.getValue();
            ClassData classData = projectData.getOrCreateClassData(filePath);
            if (lineHits.size() == 0) {
                classData.setLines(new LineData[1]);
                continue;
            }
            LineData[] lines = new LineData[lineHits.lastKey() + 1];
            for (Map.Entry<Integer, Integer> hit : lineHits.entrySet()) {
                LineData lineData = new LineData(hit.getKey(), null);
                lineData.setHits(hit.getValue());
                lines[hit.getKey()] = lineData;
            }
            classData.setLines(lines);
        }
    } catch (FileNotFoundException | JsonSyntaxException e) {
        LOG.warn(e);
    } finally {
        DartAnalysisServerService.getInstance(project).execution_deleteContext(contextId);
    }
    return projectData;
}
Also used : FileNotFoundException(java.io.FileNotFoundException) Gson(com.google.gson.Gson) Project(com.intellij.openapi.project.Project) LineData(com.intellij.rt.coverage.data.LineData) JsonSyntaxException(com.google.gson.JsonSyntaxException) ClassData(com.intellij.rt.coverage.data.ClassData) SortedMap(java.util.SortedMap) BufferedReader(java.io.BufferedReader) ProcessHandler(com.intellij.execution.process.ProcessHandler) FileReader(java.io.FileReader) Map(java.util.Map) SortedMap(java.util.SortedMap) ProjectData(com.intellij.rt.coverage.data.ProjectData) Nullable(org.jetbrains.annotations.Nullable)

Example 79 with SortedMap

use of java.util.SortedMap in project indy by Commonjava.

the class IndyZabbixReporter method report.

@SuppressWarnings("rawtypes")
@Override
public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, SortedMap<String, Timer> timers) {
    final long clock = System.currentTimeMillis() / 1000;
    List<DataObject> dataObjectList = new LinkedList<DataObject>();
    for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
        DataObject dataObject = toDataObject(entry.getKey(), "", String.valueOf(entry.getValue().getValue()), clock);
        dataObjectList.add(dataObject);
    }
    for (Map.Entry<String, Counter> entry : counters.entrySet()) {
        DataObject dataObject = toDataObject(entry.getKey(), "", String.valueOf(entry.getValue().getCount()), clock);
        dataObjectList.add(dataObject);
    }
    for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
        Histogram histogram = entry.getValue();
        Snapshot snapshot = histogram.getSnapshot();
        addSnapshotDataObject(entry.getKey(), snapshot, clock, dataObjectList);
    }
    for (Map.Entry<String, Meter> entry : meters.entrySet()) {
        Meter meter = entry.getValue();
        addMeterDataObject(entry.getKey(), meter, clock, dataObjectList);
    }
    for (Map.Entry<String, Timer> entry : timers.entrySet()) {
        Timer timer = entry.getValue();
        addMeterDataObject(entry.getKey(), timer, clock, dataObjectList);
        addSnapshotDataObjectWithConvertDuration(entry.getKey(), timer.getSnapshot(), clock, dataObjectList);
    }
    try {
        SenderResult senderResult = indyZabbixSender.send(dataObjectList, clock);
        if (!senderResult.success()) {
            logger.warn("report metrics to zabbix not success!" + senderResult);
        } else if (logger.isDebugEnabled()) {
            logger.info("report metrics to zabbix success. " + senderResult);
        }
    } catch (IOException e) {
        logger.error("report metrics to zabbix error! " + e);
        e.printStackTrace();
    } catch (IndyMetricsException e) {
        logger.error("Indy metrics config error " + e);
        e.printStackTrace();
    } catch (IndyHttpException e) {
        logger.error("Indy http client error " + e);
        e.printStackTrace();
    }
}
Also used : Histogram(com.codahale.metrics.Histogram) Meter(com.codahale.metrics.Meter) IndyHttpException(org.commonjava.indy.subsys.http.IndyHttpException) IOException(java.io.IOException) LinkedList(java.util.LinkedList) Gauge(com.codahale.metrics.Gauge) Snapshot(com.codahale.metrics.Snapshot) DataObject(org.commonjava.indy.metrics.zabbix.sender.DataObject) Counter(com.codahale.metrics.Counter) Timer(com.codahale.metrics.Timer) Map(java.util.Map) SortedMap(java.util.SortedMap) SenderResult(org.commonjava.indy.metrics.zabbix.sender.SenderResult) IndyMetricsException(org.commonjava.indy.metrics.exception.IndyMetricsException)

Example 80 with SortedMap

use of java.util.SortedMap in project stanbol by apache.

the class SolrIndexInstaller method activate.

@Activate
protected void activate(ComponentContext context) {
    bc = context.getBundleContext();
    serverTracker = new ServiceTracker(bc, ManagedSolrServer.class.getName(), new ServiceTrackerCustomizer() {

        /**
                 * The servers managed by this instance
                 */
        private SortedMap<ServiceReference, ManagedSolrServer> servers = new TreeMap<ServiceReference, ManagedSolrServer>();

        @Override
        public void removedService(ServiceReference reference, Object service) {
            lock.writeLock().lock();
            try {
                servers.remove(reference);
                updateRegistration(servers);
            } finally {
                lock.writeLock().unlock();
            }
        }

        @Override
        public void modifiedService(ServiceReference reference, Object service) {
            lock.writeLock().lock();
            try {
                servers.put(reference, (ManagedSolrServer) service);
                updateRegistration(servers);
            } finally {
                lock.writeLock().unlock();
            }
        }

        @Override
        public Object addingService(ServiceReference reference) {
            ManagedSolrServer server = (ManagedSolrServer) bc.getService(reference);
            if (server != null) {
                lock.writeLock().lock();
                try {
                    servers.put(reference, server);
                    updateRegistration(servers);
                } finally {
                    lock.writeLock().unlock();
                }
            }
            return server;
        }
    });
    serverTracker.open();
}
Also used : ServiceTracker(org.osgi.util.tracker.ServiceTracker) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) SortedMap(java.util.SortedMap) ManagedSolrServer(org.apache.stanbol.commons.solr.managed.ManagedSolrServer) ServiceReference(org.osgi.framework.ServiceReference) Activate(org.apache.felix.scr.annotations.Activate)

Aggregations

SortedMap (java.util.SortedMap)216 Map (java.util.Map)162 TreeMap (java.util.TreeMap)108 HashMap (java.util.HashMap)59 Iterator (java.util.Iterator)31 NavigableMap (java.util.NavigableMap)31 ArrayList (java.util.ArrayList)27 Test (org.junit.Test)25 IOException (java.io.IOException)20 ImmutableMap (com.google.common.collect.ImmutableMap)19 JASIExpr (org.matheclipse.core.convert.JASIExpr)16 IExpr (org.matheclipse.core.interfaces.IExpr)16 List (java.util.List)15 File (java.io.File)14 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)14 ImmutableSortedMap (com.google.common.collect.ImmutableSortedMap)12 Entry (java.util.Map.Entry)12 ConcurrentNavigableMap (java.util.concurrent.ConcurrentNavigableMap)12 ConcurrentMap (java.util.concurrent.ConcurrentMap)11 LinkedHashMap (java.util.LinkedHashMap)9