Example usage for java.util List retainAll

List of usage examples for java.util List retainAll

Introduction

In this page you can find the example usage for java.util List retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this list that are contained in the specified collection (optional operation).

Usage

From source file:org.opencms.ade.galleries.CmsGalleryService.java

/**
 * @see org.opencms.ade.galleries.shared.rpc.I_CmsGalleryService#loadVfsEntryBean(java.lang.String, java.lang.String)
 *//*  w w  w  . j  av a 2s .  co  m*/
public CmsVfsEntryBean loadVfsEntryBean(String path, String filter) throws CmsRpcException {

    try {
        if (CmsStringUtil.isEmpty(filter)) {

            CmsObject cms = OpenCms.initCmsObject(getCmsObject());
            cms.getRequestContext().setSiteRoot("");
            if (!cms.existsResource(path, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
                String startFolder = CmsStringUtil.joinPaths(path,
                        getWorkplaceSettings().getUserSettings().getStartFolder());
                if (cms.existsResource(startFolder, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
                    path = startFolder;
                }
            }
            CmsResource optionRes = cms.readResource(path);
            String title = cms.readPropertyObject(optionRes, CmsPropertyDefinition.PROPERTY_TITLE, false)
                    .getValue();
            if (CmsStringUtil.isEmpty(title)) {
                title = path;
            }
            CmsVfsEntryBean entryBean = internalCreateVfsEntryBean(getCmsObject(), optionRes, title, true,
                    isEditable(cms, optionRes), null, false);
            return entryBean;
        } else {
            filter = filter.toLowerCase();
            CmsObject cms = OpenCms.initCmsObject(getCmsObject());
            cms.getRequestContext().setSiteRoot("");
            if (!cms.existsResource(path, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
                String startFolder = CmsStringUtil.joinPaths(path,
                        getWorkplaceSettings().getUserSettings().getStartFolder());
                if (cms.existsResource(startFolder, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
                    path = startFolder;
                }
            }
            CmsResource optionRes = cms.readResource(path);
            List<CmsResource> folders = cms.readResources(optionRes.getRootPath(),
                    CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireFolder());
            folders.add(optionRes);
            Set<CmsResource> folderSet = Sets.newHashSet(folders);
            List<CmsResource> titleResources = cms.readResourcesWithProperty(path,
                    CmsPropertyDefinition.PROPERTY_TITLE);
            titleResources.retainAll(folderSet);
            Set<CmsResource> filterMatches = Sets.newHashSet();
            for (CmsResource folder : folderSet) {
                if (folder.getName().toLowerCase().contains(filter)) {
                    filterMatches.add(folder);
                    titleResources.remove(folder); // we don't need to check the title if the name already matched
                }
            }
            for (CmsResource titleRes : titleResources) {
                CmsProperty prop = cms.readPropertyObject(titleRes, CmsPropertyDefinition.PROPERTY_TITLE,
                        false);
                String title = prop.getValue();
                if ((title != null) && title.toLowerCase().contains(filter)) {
                    filterMatches.add(titleRes);
                }
            }
            Set<String> filterMatchAncestorPaths = Sets.newHashSet();
            if (filterMatches.size() > 0) {
                for (CmsResource filterMatch : filterMatches) {
                    String currentPath = filterMatch.getRootPath();
                    while (currentPath != null) {
                        filterMatchAncestorPaths.add(currentPath);
                        currentPath = CmsResource.getParentFolder(currentPath);
                    }
                }
                Set<String> allPaths = Sets.newHashSet();
                Set<String> parentPaths = Sets.newHashSet();
                for (CmsResource folder : folderSet) {
                    allPaths.add(folder.getRootPath());
                    String parent = CmsResource.getParentFolder(folder.getRootPath());
                    if (parent != null) {
                        parentPaths.add(parent);
                    }
                }
                parentPaths.retainAll(allPaths);

                Set<CmsResource> filterMatchAncestors = Sets.newHashSet();
                for (CmsResource folderRes : folderSet) {
                    if (filterMatchAncestorPaths.contains(folderRes.getRootPath())) {
                        filterMatchAncestors.add(folderRes);
                    }
                }
                Map<String, CmsResource> resourcesByPath = Maps.newHashMap();
                for (CmsResource treeRes : filterMatchAncestors) {
                    resourcesByPath.put(treeRes.getRootPath(), treeRes);
                }
                Multimap<CmsResource, CmsResource> childMap = ArrayListMultimap.create();
                for (CmsResource res : filterMatchAncestors) {
                    CmsResource parent = resourcesByPath.get(CmsResource.getParentFolder(res.getRootPath()));
                    if (parent != null) {
                        childMap.put(parent, res);
                    }
                }
                return buildVfsEntryBeanForQuickSearch(optionRes, childMap, filterMatches, parentPaths, true);
            } else {
                return null;
            }
        }
    } catch (Throwable e) {
        error(e);
        return null;
    }
}

From source file:fr.paris.lutece.util.datatable.DataTableManager.java

/**
 * Apply filters on an objects list, sort it and update pagination values.
 * @param request The request//from  www  . j av  a2 s  .  com
 * @param items Collection of objects to filter, sort and paginate
 */
public void filterSortAndPaginate(HttpServletRequest request, List<T> items) {
    List<T> filteredSortedPaginatedItems = new ArrayList<T>(items);

    boolean bSubmitedDataTable = hasDataTableFormBeenSubmited(request);

    // FILTER
    Collection<DataTableFilter> listFilters = _filterPanel.getListFilter();
    boolean bUpdateFilter = false;
    boolean bResetFilter = false;

    // We check if filters must be updated or cleared
    if (bSubmitedDataTable) {
        bResetFilter = StringUtils.equals(
                request.getParameter(FilterPanel.PARAM_FILTER_PANEL_PREFIX + FilterPanel.PARAM_RESET_FILTERS),
                Boolean.TRUE.toString());
        bUpdateFilter = true;

        if (!bResetFilter) {
            bUpdateFilter = StringUtils.equals(
                    request.getParameter(
                            FilterPanel.PARAM_FILTER_PANEL_PREFIX + FilterPanel.PARAM_UPDATE_FILTERS),
                    Boolean.TRUE.toString());
        }
    }

    for (DataTableFilter filter : listFilters) {
        String strFilterValue;

        if (bSubmitedDataTable && bUpdateFilter) {
            // We update or clear filters
            strFilterValue = request
                    .getParameter(FilterPanel.PARAM_FILTER_PANEL_PREFIX + filter.getParameterName());

            if (!bResetFilter && (filter.getFilterType() == DataTableFilterType.BOOLEAN)
                    && (strFilterValue == null)) {
                strFilterValue = Boolean.FALSE.toString();
            }

            filter.setValue(strFilterValue);
        } else {
            strFilterValue = filter.getValue();
        }

        if (StringUtils.isNotBlank(strFilterValue)) {
            List<T> bufferList = new ArrayList<T>();

            for (T item : filteredSortedPaginatedItems) {
                Method method = getMethod(item, filter.getParameterName(), CONSTANT_GET);

                if ((method == null) && (filter.getFilterType() == DataTableFilterType.BOOLEAN)) {
                    method = getMethod(item, filter.getParameterName(), CONSTANT_IS);
                }

                if (method != null) {
                    try {
                        Object value = method.invoke(item);

                        if ((value != null) && strFilterValue.equals(value.toString())) {
                            bufferList.add(item);
                        }
                    } catch (Exception e) {
                        AppLogService.error(e.getMessage(), e);
                    }
                }
            }

            filteredSortedPaginatedItems.retainAll(bufferList);
        }
    }

    // SORT
    if (bSubmitedDataTable) {
        // We update the sort parameters
        String strSortedAttributeName = request.getParameter(Parameters.SORTED_ATTRIBUTE_NAME);

        if (strSortedAttributeName != null) {
            // We update sort properties
            _strSortedAttributeName = strSortedAttributeName;
            _bIsAscSort = Boolean.parseBoolean(request.getParameter(Parameters.SORTED_ASC));
        }
    }

    // We sort the items
    if (_strSortedAttributeName != null) {
        Collections.sort(filteredSortedPaginatedItems,
                new AttributeComparator(_strSortedAttributeName, _bIsAscSort));
    }

    // PAGINATION
    if (bSubmitedDataTable) {
        // We update the pagination properties
        if (_bEnablePaginator) {
            int nOldItemsPerPage = _nItemsPerPage;
            _nItemsPerPage = Paginator.getItemsPerPage(request, Paginator.PARAMETER_ITEMS_PER_PAGE,
                    _nItemsPerPage, _nDefautlItemsPerPage);

            // If the number of items per page has changed, we switch to the first page
            if (_nItemsPerPage != nOldItemsPerPage) {
                _strCurrentPageIndex = Integer.toString(1);
            } else {
                _strCurrentPageIndex = Paginator.getPageIndex(request, Paginator.PARAMETER_PAGE_INDEX,
                        _strCurrentPageIndex);
            }
        } else {
            _strCurrentPageIndex = Integer.toString(1);
            _nItemsPerPage = filteredSortedPaginatedItems.size();
        }
    }

    // We paginate create the new paginator
    _paginator = new LocalizedPaginator<T>(filteredSortedPaginatedItems, _nItemsPerPage, getSortUrl(),
            Paginator.PARAMETER_PAGE_INDEX, _strCurrentPageIndex, request.getLocale());
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * Check whether given Tier is denied for the user
 *
 * @param tierName/*from   w  w w  . j  av a2  s. c o m*/
 * @return
 * @throws APIManagementException if failed to get the tiers
 */
@Override
public boolean isTierDeneid(String tierName) throws APIManagementException {
    String[] currentUserRoles;
    try {
        if (tenantId != 0) {
            /* Get the roles of the Current User */
            currentUserRoles = ((UserRegistry) ((UserAwareAPIConsumer) this).registry).getUserRealm()
                    .getUserStoreManager().getRoleListOfUser(((UserRegistry) this.registry).getUserName());
            TierPermissionDTO tierPermission;

            if (APIUtil.isAdvanceThrottlingEnabled()) {
                tierPermission = apiMgtDAO.getThrottleTierPermission(tierName, tenantId);
            } else {
                tierPermission = apiMgtDAO.getTierPermission(tierName, tenantId);
            }
            if (tierPermission == null) {
                return false;
            } else {
                List<String> currentRolesList = new ArrayList<String>(Arrays.asList(currentUserRoles));
                List<String> roles = new ArrayList<String>(Arrays.asList(tierPermission.getRoles()));
                currentRolesList.retainAll(roles);
                if (APIConstants.TIER_PERMISSION_ALLOW.equals(tierPermission.getPermissionType())) {
                    if (currentRolesList.isEmpty()) {
                        return true;
                    }
                } else {
                    if (currentRolesList.size() > 0) {
                        return true;
                    }
                }
            }
        }
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("cannot retrieve user role list for tenant" + tenantDomain, e);
    }
    return false;
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * Returns a list of tiers denied/*from   w  ww  .  j  a  v  a  2  s. com*/
 *
 * @return Set<Tier>
 */
@Override
public Set<String> getDeniedTiers() throws APIManagementException {
    Set<String> deniedTiers = new HashSet<String>();
    String[] currentUserRoles;
    try {
        if (tenantId != 0) {
            /* Get the roles of the Current User */
            currentUserRoles = ((UserRegistry) ((UserAwareAPIConsumer) this).registry).getUserRealm()
                    .getUserStoreManager().getRoleListOfUser(((UserRegistry) this.registry).getUserName());

            Set<TierPermissionDTO> tierPermissions;

            if (APIUtil.isAdvanceThrottlingEnabled()) {
                tierPermissions = apiMgtDAO.getThrottleTierPermissions(tenantId);
            } else {
                tierPermissions = apiMgtDAO.getTierPermissions(tenantId);
            }

            for (TierPermissionDTO tierPermission : tierPermissions) {
                String type = tierPermission.getPermissionType();

                List<String> currentRolesList = new ArrayList<String>(Arrays.asList(currentUserRoles));
                List<String> roles = new ArrayList<String>(Arrays.asList(tierPermission.getRoles()));
                currentRolesList.retainAll(roles);

                if (APIConstants.TIER_PERMISSION_ALLOW.equals(type)) {
                    /* Current User is not allowed for this Tier*/
                    if (currentRolesList.isEmpty()) {
                        deniedTiers.add(tierPermission.getTierName());
                    }
                } else {
                    /* Current User is denied for this Tier*/
                    if (currentRolesList.size() > 0) {
                        deniedTiers.add(tierPermission.getTierName());
                    }
                }
            }
        }
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        log.error("cannot retrieve user role list for tenant" + tenantDomain, e);
    }
    return deniedTiers;
}

From source file:org.hyperic.hq.bizapp.server.session.AppdefBossImpl.java

/**
 * Produce list of all groups where caller is authorized to modify. Exclude
 * any groups that contain the appdef entity id. Filter out any unwanted
 * groups specified by groupId array./*from  w w w. j  a v a2s . c  o m*/
 * @param entity for use in group member filtering.
 * @return List containing AppdefGroupValue.
 * 
 * XXX needs to be optimized
 */
@Transactional(readOnly = true)
public PageList<AppdefGroupValue> findAllGroupsMemberExclusive(int sessionId, PageControl pc,
        AppdefEntityID[] entities) throws PermissionException, SessionException {
    List<AppdefGroupValue> commonList = new ArrayList<AppdefGroupValue>();

    for (int i = 0; i < entities.length; i++) {
        AppdefEntityID eid = entities[i];
        Resource resource = resourceManager.findResource(eid);
        List<AppdefGroupValue> result = findAllGroupsMemberExclusive(sessionId, pc, eid, new Integer[] {},
                resource.getPrototype());

        if (i == 0) {
            commonList.addAll(result);
        } else {
            commonList.retainAll(result);
        }

        if (commonList.isEmpty()) {
            // no groups in common, so exit
            break;
        }
    }

    return new PageList<AppdefGroupValue>(commonList, commonList.size());
}

From source file:au.org.ala.delta.intkey.Intkey.java

@Override
public List<Item> promptForTaxaByKeyword(String directiveName, boolean permitSelectionFromIncludedTaxaOnly,
        boolean noneKeywordAvailable, boolean includeSpecimenAsOption, MutableBoolean returnSpecimenSelected,
        List<String> returnSelectedKeywords) {

    List<Image> taxonKeywordImages = _context.getDataset().getTaxonKeywordImages();
    if (_context.getImageDisplayMode() == ImageDisplayMode.AUTO && taxonKeywordImages != null
            && !taxonKeywordImages.isEmpty()) {
        ImageDialog dlg = new ImageDialog(getMainFrame(), _context.getImageSettings(), true,
                _context.displayScaled());
        dlg.setImages(taxonKeywordImages);
        dlg.setTitle(MessageFormat.format(selectTaxonKeywordsCaption, directiveName));
        dlg.showImage(0);/*from  ww  w .  j  a v  a2 s  .  c om*/
        show(dlg);

        if (!dlg.okButtonPressed()) {
            // user cancelled
            return null;
        }

        Set<String> keywords = dlg.getSelectedKeywords();

        if (!noneKeywordAvailable) {
            keywords.remove(IntkeyContext.TAXON_KEYWORD_NONE);
        }

        List<Item> selectedTaxa = new ArrayList<Item>();

        for (String keyword : keywords) {
            selectedTaxa.addAll(_context.getTaxaForKeyword(keyword));
            returnSelectedKeywords.add(keyword);
        }

        if (permitSelectionFromIncludedTaxaOnly) {
            selectedTaxa.retainAll(_context.getIncludedTaxa());
        }

        return selectedTaxa;
    } else {
        TaxonKeywordSelectionDialog dlg = new TaxonKeywordSelectionDialog(getMainFrame(), _context,
                directiveName.toUpperCase(), permitSelectionFromIncludedTaxaOnly, includeSpecimenAsOption,
                returnSpecimenSelected);
        show(dlg);
        returnSelectedKeywords.addAll(dlg.getSelectedKeywords());
        return dlg.getSelectedTaxa();
    }
}

From source file:au.org.ala.delta.intkey.Intkey.java

@Override
public List<Character> promptForCharactersByKeyword(String directiveName,
        boolean permitSelectionFromIncludedCharactersOnly, boolean noneKeywordAvailable,
        List<String> returnSelectedKeywords) {
    List<Image> characterKeywordImages = _context.getDataset().getCharacterKeywordImages();
    if (_context.getImageDisplayMode() == ImageDisplayMode.AUTO && characterKeywordImages != null
            && !characterKeywordImages.isEmpty()) {
        ImageDialog dlg = new ImageDialog(getMainFrame(), _context.getImageSettings(), true,
                _context.displayScaled());
        dlg.setImages(characterKeywordImages);
        dlg.showImage(0);/*  w w w  .j a  v  a 2  s.c  om*/
        dlg.setTitle(MessageFormat.format(selectCharacterKeywordsCaption, directiveName));

        show(dlg);

        if (!dlg.okButtonPressed()) {
            // user cancelled
            return null;
        }

        Set<String> keywords = dlg.getSelectedKeywords();

        if (!noneKeywordAvailable) {
            keywords.remove(IntkeyContext.CHARACTER_KEYWORD_NONE);
        }

        List<Character> selectedCharacters = new ArrayList<Character>();

        for (String keyword : keywords) {
            selectedCharacters.addAll(_context.getCharactersForKeyword(keyword));
            returnSelectedKeywords.add(keyword);
        }

        if (permitSelectionFromIncludedCharactersOnly) {
            selectedCharacters.retainAll(_context.getIncludedCharacters());
        }

        return selectedCharacters;
    } else {
        CharacterKeywordSelectionDialog dlg = new CharacterKeywordSelectionDialog(getMainFrame(), _context,
                directiveName.toUpperCase(), permitSelectionFromIncludedCharactersOnly);
        show(dlg);
        returnSelectedKeywords.addAll(dlg.getSelectedKeywords());
        return dlg.getSelectedCharacters();
    }
}

From source file:org.openbel.framework.internal.KAMStoreDaoImpl.java

@Override
public List<BelTerm> getSupportingTerms(KamNode kamNode, NamespaceFilter namespaceFilter) throws SQLException {
    List<BelTerm> termList = getSupportingTerms(kamNode);

    if (namespaceFilter != null) {
        for (FilterCriteria criterion : namespaceFilter.getFilterCriteria()) {
            NamespaceFilterCriteria nfc = (NamespaceFilterCriteria) criterion;
            Set<Integer> targetNamespaceIds = new HashSet<Integer>();
            for (Namespace ns : nfc.getValues()) {
                targetNamespaceIds.add(ns.getId());
            }//from ww w .  j a v a  2  s . c  o  m
            List<BelTerm> matchedTerms = new ArrayList<BelTerm>();
            for (BelTerm term : termList) {
                List<TermParameter> params = getTermParameters(term);
                for (TermParameter param : params) {
                    if (param.namespace != null && targetNamespaceIds.contains(param.namespace.getId())) {
                        matchedTerms.add(term);
                        break;
                    }
                }
            }
            if (criterion.isInclude()) {
                termList.retainAll(matchedTerms);
            } else {
                // must be exclude
                termList.removeAll(matchedTerms);
            }

        }
    }
    return termList;
}

From source file:org.jsweet.transpiler.typescript.Java2TypeScriptTranslator.java

@Override
public void visitTopLevel(JCCompilationUnit topLevel) {

    boolean noDefs = true;
    for (JCTree def : topLevel.defs) {
        if (def instanceof JCClassDecl) {
            if (!context.isIgnored(((JCClassDecl) def))) {
                noDefs = false;/*w ww . j a v a 2  s. c  om*/
            }
        }
    }
    // do not print the compilation unit at all if no defs are to be printed
    if (noDefs) {
        return;
    }

    isDefinitionScope = topLevel.packge.getQualifiedName().toString()
            .startsWith(JSweetConfig.LIBS_PACKAGE + ".");

    if (context.hasAnnotationType(topLevel.packge, JSweetConfig.ANNOTATION_MODULE)) {
        context.addExportedElement(
                context.getAnnotationValue(topLevel.packge, JSweetConfig.ANNOTATION_MODULE, null),
                topLevel.packge);
    }

    printIndent().print("/* Generated from Java with JSweet " + JSweetConfig.getVersionNumber()
            + " - http://www.jsweet.org */").println();
    PackageSymbol rootPackage = context.getFirstEnclosingRootPackage(topLevel.packge);
    if (rootPackage != null) {
        if (!checkRootPackageParent(topLevel, rootPackage, (PackageSymbol) rootPackage.owner)) {
            return;
        }
    }
    context.importedTopPackages.clear();
    context.rootPackages.add(rootPackage);
    if (context.useModules && context.rootPackages.size() > 1) {
        if (!context.reportedMultipleRootPackages) {
            report(topLevel.getPackageName(), JSweetProblem.MULTIPLE_ROOT_PACKAGES_NOT_ALLOWED_WITH_MODULES,
                    context.rootPackages.toString());
            context.reportedMultipleRootPackages = true;
        }
        return;
    }

    topLevelPackage = context.getTopLevelPackage(topLevel.packge);
    if (topLevelPackage != null) {
        context.topLevelPackageNames.add(topLevelPackage.getQualifiedName().toString());
    }

    footer.delete(0, footer.length());

    setCompilationUnit(topLevel);

    String packge = topLevel.packge.toString();

    globalModule = JSweetConfig.GLOBALS_PACKAGE_NAME.equals(packge)
            || packge.endsWith("." + JSweetConfig.GLOBALS_PACKAGE_NAME);
    String rootRelativePackageName = "";
    if (!globalModule) {
        rootRelativePackageName = getRootRelativeName(topLevel.packge);
        if (rootRelativePackageName.length() == 0) {
            globalModule = true;
        }
    }

    List<String> packageSegments = new ArrayList<String>(Arrays.asList(rootRelativePackageName.split("\\.")));
    packageSegments.retainAll(JSweetConfig.TS_TOP_LEVEL_KEYWORDS);
    if (!packageSegments.isEmpty()) {
        report(topLevel.getPackageName(), JSweetProblem.PACKAGE_NAME_CONTAINS_KEYWORD, packageSegments);
    }

    // generate requires by looking up imported external modules

    for (JCImport importDecl : topLevel.getImports()) {

        TreeScanner importedModulesScanner = new TreeScanner() {
            @Override
            public void scan(JCTree tree) {
                if (tree instanceof JCFieldAccess) {
                    JCFieldAccess qualified = (JCFieldAccess) tree;
                    if (qualified.sym != null) {
                        // regular import case (qualified.sym is a package)
                        if (context.hasAnnotationType(qualified.sym, JSweetConfig.ANNOTATION_MODULE)) {
                            String actualName = context.getAnnotationValue(qualified.sym,
                                    JSweetConfig.ANNOTATION_MODULE, null);
                            useModule(true, null, importDecl, qualified.name.toString(), actualName,
                                    ((PackageSymbol) qualified.sym));
                        }
                    } else {
                        // static import case (imported fields and methods)
                        if (qualified.selected instanceof JCFieldAccess) {
                            JCFieldAccess qualifier = (JCFieldAccess) qualified.selected;
                            if (qualifier.sym != null) {
                                try {
                                    for (Symbol importedMember : qualifier.sym.getEnclosedElements()) {
                                        if (qualified.name.equals(importedMember.getSimpleName())) {
                                            if (context.hasAnnotationType(importedMember,
                                                    JSweetConfig.ANNOTATION_MODULE)) {
                                                String actualName = context.getAnnotationValue(importedMember,
                                                        JSweetConfig.ANNOTATION_MODULE, null);
                                                useModule(true, null, importDecl,
                                                        importedMember.getSimpleName().toString(), actualName,
                                                        importedMember);
                                                break;
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    // TODO: sometimes,
                                    // getEnclosedElement
                                    // fails because of string types
                                    // (find
                                    // out why if possible)
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
                super.scan(tree);
            }
        };
        importedModulesScanner.scan(importDecl.qualid);
    }

    for (JCImport importDecl : topLevel.getImports()) {
        if (importDecl.qualid instanceof JCFieldAccess) {
            JCFieldAccess qualified = (JCFieldAccess) importDecl.qualid;
            String importedName = qualified.name.toString();
            if (importDecl.isStatic() && (qualified.selected instanceof JCFieldAccess)) {
                qualified = (JCFieldAccess) qualified.selected;
            }
            if (qualified.sym instanceof ClassSymbol) {
                ClassSymbol importedClass = (ClassSymbol) qualified.sym;
                if (Util.isSourceType(importedClass) && !importedClass.getQualifiedName().toString()
                        .startsWith(JSweetConfig.LIBS_PACKAGE + ".")) {
                    String importedModule = importedClass.sourcefile.getName();
                    if (importedModule.equals(compilationUnit.sourcefile.getName())) {
                        continue;
                    }
                    String pathToImportedClass = Util.getRelativePath(
                            new File(compilationUnit.sourcefile.getName()).getParent(), importedModule);
                    pathToImportedClass = pathToImportedClass.substring(0, pathToImportedClass.length() - 5);
                    if (!pathToImportedClass.startsWith(".")) {
                        pathToImportedClass = "./" + pathToImportedClass;
                    }

                    Symbol symbol = qualified.sym.getEnclosingElement();
                    while (!(symbol instanceof PackageSymbol)) {
                        importedName = symbol.getSimpleName().toString();
                        symbol = symbol.getEnclosingElement();
                    }
                    if (symbol != null) {
                        useModule(false, (PackageSymbol) symbol, importDecl, importedName,
                                pathToImportedClass.replace('\\', '/'), null);
                    }
                }
            }
        }
    }

    if (context.useModules) {
        TreeScanner usedTypesScanner = new TreeScanner() {

            private void checkType(TypeSymbol type) {
                if (type instanceof ClassSymbol) {
                    if (type.getEnclosingElement().equals(compilationUnit.packge)) {
                        String importedModule = ((ClassSymbol) type).sourcefile.getName();
                        if (!importedModule.equals(compilationUnit.sourcefile.getName())) {
                            importedModule = "./" + new File(importedModule).getName();
                            importedModule = importedModule.substring(0, importedModule.length() - 5);
                            useModule(false, (PackageSymbol) type.getEnclosingElement(), null,
                                    type.getSimpleName().toString(), importedModule, null);
                        }
                    }
                }
            }

            @Override
            public void scan(JCTree t) {
                if (t != null && t.type != null && t.type.tsym instanceof ClassSymbol) {
                    if (!(t instanceof JCTypeApply)) {
                        checkType(t.type.tsym);
                    }
                }
                super.scan(t);
            }

        };
        usedTypesScanner.scan(compilationUnit);
    }

    // require root modules when using fully qualified names or reserved
    // keywords
    TreeScanner inlinedModuleScanner = new TreeScanner() {
        Stack<JCTree> stack = new Stack<>();

        public void scan(JCTree t) {
            if (t != null) {
                stack.push(t);
                try {
                    super.scan(t);
                } finally {
                    stack.pop();
                }
            }
        }

        @SuppressWarnings("unchecked")
        public <T extends JCTree> T getParent(Class<T> type) {
            for (int i = this.stack.size() - 2; i >= 0; i--) {
                if (type.isAssignableFrom(this.stack.get(i).getClass())) {
                    return (T) this.stack.get(i);
                }
            }
            return null;
        }

        public void visitIdent(JCIdent identifier) {
            if (identifier.sym instanceof PackageSymbol) {
                // ignore packages in imports
                if (getParent(JCImport.class) != null) {
                    return;
                }
                boolean isSourceType = false;
                for (int i = stack.size() - 2; i >= 0; i--) {
                    JCTree tree = stack.get(i);
                    if (!(tree instanceof JCFieldAccess)) {
                        break;
                    } else {
                        JCFieldAccess fa = (JCFieldAccess) tree;
                        if ((fa.sym instanceof ClassSymbol) && Util.isSourceType((ClassSymbol) fa.sym)) {
                            isSourceType = true;
                            break;
                        }
                    }
                }
                if (!isSourceType) {
                    return;
                }
                PackageSymbol identifierPackage = (PackageSymbol) identifier.sym;
                String pathToModulePackage = Util.getRelativePath(compilationUnit.packge, identifierPackage);
                if (pathToModulePackage == null) {
                    return;
                }
                File moduleFile = new File(new File(pathToModulePackage), JSweetConfig.MODULE_FILE_NAME);
                if (!identifierPackage.getSimpleName().toString()
                        .equals(compilationUnit.packge.getSimpleName().toString())) {
                    useModule(false, identifierPackage, identifier,
                            identifierPackage.getSimpleName().toString(),
                            moduleFile.getPath().replace('\\', '/'), null);
                }
            } else if (identifier.sym instanceof ClassSymbol) {
                if (JSweetConfig.GLOBALS_PACKAGE_NAME
                        .equals(identifier.sym.getEnclosingElement().getSimpleName().toString())) {
                    String pathToModulePackage = Util.getRelativePath(compilationUnit.packge,
                            identifier.sym.getEnclosingElement());
                    if (pathToModulePackage == null) {
                        return;
                    }
                    File moduleFile = new File(new File(pathToModulePackage), JSweetConfig.MODULE_FILE_NAME);
                    if (!identifier.sym.getEnclosingElement()
                            .equals(compilationUnit.packge.getSimpleName().toString())) {
                        useModule(false, (PackageSymbol) identifier.sym.getEnclosingElement(), identifier,
                                JSweetConfig.GLOBALS_PACKAGE_NAME, moduleFile.getPath().replace('\\', '/'),
                                null);
                    }
                }
            }
        }

        @Override
        public void visitApply(JCMethodInvocation invocation) {
            // TODO: same for static variables
            if (invocation.meth instanceof JCIdent && JSweetConfig.TS_STRICT_MODE_KEYWORDS
                    .contains(invocation.meth.toString().toLowerCase())) {
                PackageSymbol invocationPackage = (PackageSymbol) ((JCIdent) invocation.meth).sym
                        .getEnclosingElement().getEnclosingElement();
                String rootRelativeInvocationPackageName = getRootRelativeName(invocationPackage);
                if (rootRelativeInvocationPackageName.indexOf('.') == -1) {
                    super.visitApply(invocation);
                    return;
                }
                String targetRootPackageName = rootRelativeInvocationPackageName.substring(0,
                        rootRelativeInvocationPackageName.indexOf('.'));
                String pathToReachRootPackage = Util.getRelativePath(
                        "/" + compilationUnit.packge.getQualifiedName().toString().replace('.', '/'),
                        "/" + targetRootPackageName);
                if (pathToReachRootPackage == null) {
                    super.visitApply(invocation);
                    return;
                }
                File moduleFile = new File(new File(pathToReachRootPackage), JSweetConfig.MODULE_FILE_NAME);
                if (!invocationPackage.toString().equals(compilationUnit.packge.getSimpleName().toString())) {
                    useModule(false, invocationPackage, invocation, targetRootPackageName,
                            moduleFile.getPath().replace('\\', '/'), null);
                }
            }
            super.visitApply(invocation);
        }

    };
    // TODO: change the way qualified names are handled (because of new
    // module organization)
    // inlinedModuleScanner.scan(compilationUnit);

    if (!globalModule && !context.useModules) {
        printIndent();
        if (isDefinitionScope) {
            print("declare ");
        }
        print("namespace ").print(rootRelativePackageName).print(" {").startIndent().println();
    }

    for (JCTree def : topLevel.defs) {
        mainMethod = null;

        printIndent();
        int pos = getCurrentPosition();
        print(def);
        if (getCurrentPosition() == pos) {
            removeLastIndent();
            continue;
        }
        println().println();
    }
    if (!globalModule && !context.useModules) {
        removeLastChar().endIndent().printIndent().print("}").println();
    }

    if (footer.length() > 0) {
        println().print(footer.toString());
    }

    globalModule = false;

}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

private void notificationToInstructors(AssignmentSubmission submission, Assignment assignment) {
    String notiOption = assignment.getProperties()
            .get(AssignmentConstants.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_VALUE);
    if (notiOption != null
            && !notiOption.equals(AssignmentConstants.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_NONE)) {
        // need to send notification email
        String context = assignment.getContext();
        String assignmentReference = AssignmentReferenceReckoner.reckoner().assignment(assignment).reckon()
                .getReference();/* ww  w .j  av a  2s.  c  o  m*/

        // compare the list of users with the receive.notifications and list of users who can actually grade this assignment
        List<User> receivers = allowReceiveSubmissionNotificationUsers(context);
        List allowGradeAssignmentUsers = allowGradeAssignmentUsers(assignmentReference);
        receivers.retainAll(allowGradeAssignmentUsers);

        String messageBody = emailUtil.getNotificationMessage(submission, "submission");

        if (notiOption.equals(AssignmentConstants.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_EACH)) {
            // send the message immediately
            emailService.sendToUsers(receivers, emailUtil.getHeaders(null, "submission"), messageBody);
        } else if (notiOption.equals(AssignmentConstants.ASSIGNMENT_INSTRUCTOR_NOTIFICATIONS_DIGEST)) {
            // just send plain/text version for now
            String digestMsgBody = emailUtil.getPlainTextNotificationMessage(submission, "submission");

            // digest the message to each user
            for (User user : receivers) {
                digestService.digest(user.getId(), emailUtil.getSubject("submission"), digestMsgBody);
            }
        }
    }
}