Example usage for com.google.common.collect Sets newTreeSet

List of usage examples for com.google.common.collect Sets newTreeSet

Introduction

In this page you can find the example usage for com.google.common.collect Sets newTreeSet.

Prototype

public static <E extends Comparable> TreeSet<E> newTreeSet() 

Source Link

Document

Creates a mutable, empty TreeSet instance sorted by the natural sort ordering of its elements.

Usage

From source file:org.obiba.opal.core.service.security.DefaultSubjectAclService.java

@Override
public void deleteNodePermissions(String domain, String node) {
    Set<Subject> subjects = Sets.newTreeSet();
    for (SubjectAcl acl : find(domain, node)) {
        subjects.add(acl.getSubject());/*w  ww  .  ja  v a2 s. co m*/
        delete(acl);
    }
    notifyListeners(subjects);
}

From source file:org.ambraproject.wombat.config.theme.InternalTheme.java

@Override
protected Collection<String> fetchStaticResourcePaths(String root) throws IOException {
    String contextRoot = resourceRoot + root;

    Set<String> relativePaths = Sets.newTreeSet();
    Deque<String> queue = new ArrayDeque<>();
    queue.add(contextRoot);//  w w w  . ja v a  2  s  .  c  o m
    while (!queue.isEmpty()) {
        String path = queue.removeFirst();
        if (path.endsWith("/")) {
            Set<String> childPaths = servletContext.getResourcePaths(path);
            if (childPaths != null) {
                for (String childPath : childPaths) {
                    queue.add(childPath);
                }
            }
        } else {
            relativePaths.add(path.substring(contextRoot.length()));
        }
    }
    return relativePaths;
}

From source file:com.threerings.presents.tools.cpp.GenCPPStreamableTask.java

/**
 * Processes a resolved Streamable class instance.
 *///from  w w  w .jav  a 2 s  . co m
protected void processClass(Class<?> sclass) throws IOException {
    if (!Streamable.class.isAssignableFrom(sclass) || ((sclass.getModifiers() & Modifier.INTERFACE) != 0)
            || DSet.class.equals(sclass) || (InvocationMarshaller.class.isAssignableFrom(sclass)
                    && !InvocationMarshaller.class.equals(sclass))) {
        //            System.err.println("Skipping " + sclass.getName() + "...");
        return;
    }

    System.err.println("Generating " + sclass.getName());

    // see if our parent also implements Streamable
    boolean needSuper = Streamable.class.isAssignableFrom(sclass.getSuperclass())
            && !NONSUPER.contains(sclass.getSuperclass());

    Map<String, Object> ctx = Maps.newHashMap();
    ctx.put("superclassStreamable", needSuper);
    ctx.put("name", sclass.getSimpleName());
    ctx.put("namespaces", makeNamespaces(sclass));
    ctx.put("javaName", sclass.getName());
    ctx.put("namespace", CPPUtil.makeNamespace(sclass));

    Set<String> headerIncludes = Sets.newTreeSet();
    Set<String> implIncludes = Sets.newTreeSet();
    if (needSuper) {
        ctx.put("super", makeCPPName(sclass.getSuperclass()));
        addInclude(sclass.getSuperclass(), headerIncludes);
    } else {
        ctx.put("super", "Streamable");
        headerIncludes.add("presents/Streamable.h");
    }

    List<CPPField> fields = Lists.newArrayList();
    ctx.put("fields", fields);
    for (Field field : sclass.getDeclaredFields()) {
        int mods = field.getModifiers();
        if (!Modifier.isStatic(mods) && !Modifier.isTransient(mods)) {
            CPPField cppField = new CPPField(field);
            fields.add(cppField);
            CPPType type = cppField.type;
            while (type != null) {
                if (CPPType.JAVA_LIST_FIXED.equals(type.fixed)) {
                    implIncludes.add("presents/Streamer.h");
                }
                if (type.representationImport != null) {
                    headerIncludes.add(type.representationImport);
                }
                type = type.dependent;
            }
        }
    }
    String inStream, outStream;
    if (fields.isEmpty() && !needSuper) {
        inStream = "/*in*/";
        outStream = "/*out*/";
    } else {
        inStream = "in";
        outStream = "out";

    }
    ctx.put("inStreamArg", inStream);
    ctx.put("outStreamArg", outStream);

    // now write all that out to the target source file
    ctx.put("includes", headerIncludes);
    writeTemplate(HEADER_TMPL, makePath(_cpproot, sclass, ".h"), ctx);

    ctx.put("includes", implIncludes);
    writeTemplate(CPP_TMPL, makePath(_cpproot, sclass, ".cpp"), ctx);
}

From source file:de.faustedition.genesis.lines.VerseManager.java

public void register(FaustGraph faustGraph, Neo4jTextRepository<JsonNode> textRepo, MaterialUnit mu,
        LayerNode<JsonNode> transcript) {

    for (VerseInterval vi : registeredFor(transcript)) {
        ((GraphVerseInterval) vi).node.delete();
    }//from ww w .  ja v a2  s .  c  o  m
    Index<Node> verseTextIndex = faustGraph.getDb().index().forNodes(INDEX_VERSE_FULLTEXT,
            MapUtil.stringMap(IndexManager.PROVIDER, "lucene", "type", "fulltext"));

    final SortedSet<Long> verses = Sets.newTreeSet();
    for (Layer<JsonNode> verse : textRepo
            .query(and(text(transcript), name(new Name(TextConstants.TEI_NS, "l"))))) {

        //final Matcher verseNumberMatcher = VERSE_NUMBER_PATTERN.matcher(Objects.firstNonNull(verse.data().path("n").getTextValue(), ""));
        long lineNum = verse.data().get("n") != null ? verse.data().get("n").asLong(-1) : -1;

        if (lineNum >= 0) {
            verses.add(lineNum);
        }

        Anchor<JsonNode> anchor = Iterables.getOnlyElement(verse.getAnchors());
        try {
            String verseText = anchor.getText().read(anchor.getRange());
            LOG.trace("Indexing verse: " + verseText);
            verseTextIndex.add(((LayerNode) verse).node, "fulltext", Normalization.normalize(verseText));

        } catch (IOException e) {
            LOG.error("Error indexing line " + lineNum);
        }
    }

    Index<Node> verseIndex = faustGraph.getDb().index().forNodes(INDEX_VERSE_INTERVAL);

    long start = -1;
    long next = -1;
    for (Iterator<Long> it = verses.iterator(); it.hasNext();) {
        final long verse = it.next();
        if (verse == next) {
            next++;
        } else if (verse > next) {
            if (start >= 0) {
                final GraphVerseInterval vi = new GraphVerseInterval(faustGraph.getDb(), (int) start,
                        (int) next - 1);
                vi.setTranscript(transcript);
                verseIndex.add(vi.node, "start", ValueContext.numeric(vi.getStart()));
                verseIndex.add(vi.node, "end", ValueContext.numeric(vi.getEnd()));

            }

            start = verse;
            next = verse + 1;
        }

        if (!it.hasNext() && start >= 0) {
            final GraphVerseInterval vi = new GraphVerseInterval(faustGraph.getDb(), (int) start, (int) verse);
            vi.setTranscript(transcript);
            verseIndex.add(vi.node, "start", ValueContext.numeric(vi.getStart()));
            verseIndex.add(vi.node, "end", ValueContext.numeric(vi.getEnd()));

        }
    }
    if (LOG.isDebugEnabled()) {
        // TODO LOG.debug("Registered verse intervals {} for {}", Iterables.toString(registeredFor(session, transcript)), transcript);
    }
}

From source file:org.opennms.netmgt.dao.support.DomainResourceType.java

private Set<String> findDomainNames() {
    Set<String> domainNames = Sets.newTreeSet();

    // Get all of the non-numeric directory names in the RRD directory; these
    // are the names of the domains that have performance data
    for (ResourcePath child : m_resourceStorageDao.children(ResourcePath.get(ResourceTypeUtils.SNMP_DIRECTORY),
            2)) {/*from   ww  w.ja  va  2s  . co m*/
        try {
            // if the directory name is an integer
            Integer.parseInt(child.getName());
            continue;
        } catch (NumberFormatException e) {
            domainNames.add(child.getName());
        }
    }

    return domainNames;
}

From source file:org.eclipse.wb.internal.core.utils.ast.AstCodeGeneration.java

/**
 * @return the end-of-line marker for given {@link StringBuffer}.
 *///from   ww  w  .  j ava2s . com
private static String getEndOfLineForBuffer(Document document) throws Exception {
    // prepare set of existing EOL's
    Set<String> existingMarkers = Sets.newTreeSet();
    {
        int numberOfLines = document.getNumberOfLines();
        for (int i = 0; i < numberOfLines; i++) {
            String delimiter = document.getLineDelimiter(i);
            if (delimiter != null) {
                existingMarkers.add(delimiter);
            }
        }
    }
    // return default or first EOL
    if (existingMarkers.isEmpty() || existingMarkers.contains(DEFAULT_END_OF_LINE)) {
        return DEFAULT_END_OF_LINE;
    } else {
        return existingMarkers.iterator().next();
    }
}

From source file:ezbake.groups.cli.commands.user.GetUserAuthorizations.java

private static Set<Long> getAuthorizations(EzGroupsGraphImpl graph, BaseVertex.VertexType userType,
        String userId, List<String> appFilterChain) throws GroupQueryException, UserNotFoundException {
    Set<Long> auths = Sets.newHashSet();

    // Only get auths if the user exists
    User user;//from   w  w w  . j  av a  2 s. c  o m
    try {
        user = graph.getUser(userType, userId);
        if (!user.isActive()) {
            return auths; // just don't get groups
        }
    } catch (UserNotFoundException | InvalidVertexTypeException e) {
        return auths; // just don't get groups
    }

    // Add the user's own index
    auths.add(user.getIndex());

    // This can sometimes be null
    if (appFilterChain == null) {
        appFilterChain = Collections.emptyList();
    }

    // These are the groups the user has on their own
    Set<Group> userGroups = getUserGroups(graph, userType, userId, false, false);
    logger.debug("Initial user groups: {}", userGroups);

    // These are the groups the apps always include, even if the user doesn't have access
    List<Set<Group>> appsGroups = getAuthorizationsForApps(graph, appFilterChain, false);
    Set<Long> appsFilter = Sets.newHashSet(); // This is the intersection of all app auths
    Set<Long> groupsAppsAlwaysInclude = Sets.newTreeSet(); // This is all the groups the apps include anyways
    for (Set<Group> appGroup : appsGroups) {
        Set<Long> indices = Sets.newTreeSet();
        for (Group group : appGroup) {
            indices.add(group.getIndex());
            if (group.isRequireOnlyApp()) {
                groupsAppsAlwaysInclude.add(group.getIndex());
            }
        }
        appsFilter.retainAll(indices);
    }
    logger.debug("Apps filter: {}", appsFilter);

    if (userType == BaseVertex.VertexType.USER) {
        // Split groups into 2 sets - those that users always have (even if app doesn't) and those that users only have if app has too
        Set<Long> groupsUserHasRegardless = Sets.newHashSet(auths);
        Set<Long> groupsDependingOnApp = Sets.newHashSet();
        for (Group g : userGroups) {
            if (g.isRequireOnlyUser()) {
                groupsUserHasRegardless.add(g.getIndex());
            } else {
                groupsDependingOnApp.add(g.getIndex());
            }
        }

        // Filter the groups that depend on the app
        if (!groupsDependingOnApp.isEmpty()) {
            logger.debug("Groups depending on app: {}", groupsDependingOnApp);
            groupsDependingOnApp = Sets.intersection(groupsDependingOnApp, appsFilter);
        }

        logger.debug("Groups user has regardless: {}", groupsUserHasRegardless);
        // Now union the sets to get the users final list
        auths = Sets.union(groupsUserHasRegardless, groupsDependingOnApp);
    } else if (userType == BaseVertex.VertexType.APP_USER) {
        // What to do here?
        Set<Long> appAuths = Sets.newHashSet(auths);
        for (Group g : userGroups) {
            appAuths.add(g.getIndex());
        }
        auths = appAuths;
    }

    logger.debug("User auths before union: {}", auths);
    return Sets.union(auths, groupsAppsAlwaysInclude);
}

From source file:org.eclipse.wb.internal.xwt.model.util.NameSupport.java

/**
 * Traverses the entire hierarchy and gathers set of existing names.
 *//*from ww  w  .ja v  a2  s .  c  o  m*/
private static Set<String> getExistingNames(XmlObjectInfo object) {
    final Set<String> resultSet = Sets.newTreeSet();
    object.getRootXML().accept(new ObjectInfoVisitor() {
        @Override
        public void endVisit(ObjectInfo object) throws Exception {
            if (object instanceof XmlObjectInfo) {
                XmlObjectInfo xmlObject = (XmlObjectInfo) object;
                if (XmlObjectUtils.isImplicit(xmlObject)) {
                    return;
                }
                String name = getName(xmlObject);
                if (name != null) {
                    resultSet.add(name);
                }
            }
        }
    });
    return resultSet;
}

From source file:blackboard.plugin.hayabusa.provider.ThemeProvider.java

@Override
public Iterable<Command> getCommands() {
    List<Theme> themes = ThemeManagerFactory.getInstance().getAllThemes();
    Set<Command> commands = Sets.newTreeSet();
    Context bbCtxt = ContextManagerFactory.getInstance().getContext();
    NavigationItem ni = null;//from   ww  w.  ja va2s.  co m
    List<PortalBranding> portalBrandings = null;
    PortalBranding currentPortalBranding = null;
    Branding branding = null;
    ColorPalette colorPalette = null;
    Theme currentTheme = null;
    try {
        NavigationItemDbLoader niDbLoader = NavigationItemDbLoader.Default.getInstance();
        ni = niDbLoader.loadByInternalHandle("pa_customize_brand");
        NavigationItemControl nic = NavigationItemControl.createInstance(ni);
        if (!nic.userHasAccess()) {
            return commands;
        }
        currentTheme = BrandingUtil.getCurrentBrandTheme(bbCtxt.getHostName());
        branding = BrandingManager.Factory.getInstance().getBrandingByHostNameAndRole(bbCtxt.getHostName(),
                null);
        ColorPaletteManager colorPaletteManager = ColorPaletteManagerFactory.getInstance();
        colorPalette = colorPaletteManager.getColorPaletteByBrandingId(branding.getId());

        PortalBrandingDbLoader pbLoader = PortalBrandingDbLoader.Default.getInstance();
        portalBrandings = pbLoader.loadByThemeId(currentTheme.getId());
    } catch (Exception e) {
        throw new PersistenceRuntimeException(e);
    }

    for (PortalBranding pb : portalBrandings) {
        if (pb.isDefault()) {
            currentPortalBranding = pb;
            break;
        }
    }
    for (Theme theme : themes) {
        String themeExtRef = theme.getExtRef();

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("cmd", "save");
        params.put("brand_id", branding.getId().getExternalString());
        params.put("pageType", "Navigation");
        params.put("usesCustomBrand", "true");
        params.put("startThemeExtRef", currentTheme.getExtRef());
        String colorExtRef = "";
        if (colorPalette != null) {
            colorExtRef = colorPalette.getExtRef();
        }
        params.put("startPaletteExtRef", colorExtRef);
        params.put("color_palette_extRef", colorExtRef);
        params.put("theme_extRef", themeExtRef);
        params.put("deleteBrandCss", "false");
        params.put("tabStyle", currentTheme.getTabStyle().getAbbrevString());
        params.put("tabAlign", currentTheme.getTabAlignment().toString());
        params.put("frameSize", currentTheme.getFrameSize().toString());

        params.put("bannerImage_attachmentType", "AL");
        params.put("bannerImage_fileId", currentPortalBranding.getBannerImage());
        params.put("bannerImage_LocalFile0", "");
        params.put("bannerImageLink", currentPortalBranding.getBannerUrl());
        params.put("bannerAltText", currentPortalBranding.getBannerText());
        params.put("pde_institution_role", bbCtxt.getUser().getPortalRoleId().toExternalString());

        params.put("courseNameUsage", branding.getCourseNameUsage().toExternalString());

        params.put(NonceUtil.NONCE_KEY, NonceUtil.create(bbCtxt.getSession(), NONCE_ID, NONCE_CONTEXT));

        commands.add(new PostCommand(themeExtRef, URI, Category.THEME, params, "multipart/form-data"));
    }
    return commands;
}

From source file:org.eclipse.wb.internal.swing.model.property.editor.border.pages.SwingBorderComposite.java

/**
 * Prepares {@link FontInfo}'s for {@link Font}'s from {@link UIManager}.
 *//*  w  ww .java 2s . com*/
private static synchronized void prepareBorders() {
    if (m_borders == null) {
        m_borderKeys = Lists.newArrayList();
        m_borders = Lists.newArrayList();
        UIDefaults defaults = UIManager.getLookAndFeelDefaults();
        // prepare set of all String keys in UIManager
        Set<String> allKeys = Sets.newTreeSet();
        for (Iterator<?> I = defaults.keySet().iterator(); I.hasNext();) {
            Object key = I.next();
            if (key instanceof String) {
                allKeys.add((String) key);
            }
        }
        // add Border for each key
        for (String key : allKeys) {
            Border border = defaults.getBorder(key);
            if (border != null) {
                m_borderKeys.add(key);
                m_borders.add(border);
            }
        }
    }
}