Example usage for java.util List listIterator

List of usage examples for java.util List listIterator

Introduction

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

Prototype

ListIterator<E> listIterator();

Source Link

Document

Returns a list iterator over the elements in this list (in proper sequence).

Usage

From source file:org.collectionspace.services.authorization.spring.SpringPermissionManager.java

/**
 * deletePermissions deletes given permission on given object id for given sid
 * @param oid/*  w w  w. j  ava2  s.co  m*/
 * @param permission
 * @param sid
 */
//non-javadoc NOTE: if sid is null it would remove ACEs for all sid(s)
private void deletePermissions(ObjectIdentity oid, Permission permission,
        Sid sid) /** throws AclDataAccessException */
{
    int i = 0;
    MutableAcl acl = getAcl(oid);
    List<AccessControlEntry> acel = acl.getEntries();
    int aces = acel.size();
    if (log.isDebugEnabled()) {
        log.debug("deletePermissions: for acl oid=" + oid.toString() + " found " + aces + " aces");
    }
    ArrayList<Integer> foundAces = new ArrayList<Integer>();
    Iterator iter = acel.listIterator();
    //not possible to delete while iterating
    while (iter.hasNext()) {
        AccessControlEntry ace = (AccessControlEntry) iter.next();
        if (sid != null) {
            if (ace.getSid().equals(sid) && ace.getPermission().equals(permission)) {
                foundAces.add(i);
            }
        } else {
            if (ace.getPermission().equals(permission)) {
                foundAces.add(i);
            }
        }
        i++;
    }
    for (int j = foundAces.size() - 1; j >= 0; j--) {
        //the following operation does not work while iterating in the while loop
        acl.deleteAce(foundAces.get(j)); //autobox
    }
    provider.getProviderAclService().updateAcl(acl);

    if (log.isDebugEnabled()) {
        log.debug("deletePermissions: for acl oid=" + oid.toString() + " deleted " + i + " aces");
    }
}

From source file:com.xpn.xwiki.plugin.tag.TagPlugin.java

/**
 * Remove a tag from a document. The document is saved (minor edit) after this operation.
 * /*from ww w.  j  av a2 s. c om*/
 * @param tag tag to remove.
 * @param document the document.
 * @param context XWiki context.
 * @return the {@link TagOperationResult result} of the operation
 * @throws XWikiException if document save fails for some reason (Insufficient rights, DB access, etc).
 */
public TagOperationResult removeTagFromDocument(String tag, XWikiDocument document, XWikiContext context)
        throws XWikiException {
    List<String> tags = getTagsFromDocument(document);
    boolean needsUpdate = false;

    ListIterator<String> it = tags.listIterator();
    while (it.hasNext()) {
        if (tag.equalsIgnoreCase(it.next())) {
            needsUpdate = true;
            it.remove();
        }
    }

    if (needsUpdate) {
        setDocumentTags(document, tags, context);
        List<String> commentArgs = new ArrayList<String>();
        commentArgs.add(tag);
        String comment = context.getMessageTool().get("plugin.tag.editcomment.removed", commentArgs);

        // Since we're changing the document we need to set the new author
        document.setAuthorReference(context.getUserReference());

        context.getWiki().saveDocument(document, comment, true, context);

        return TagOperationResult.OK;
    } else {
        // Document doesn't contain this tag.
        return TagOperationResult.NO_EFFECT;
    }
}

From source file:org.apereo.portal.groups.local.searchers.PortletDefinitionSearcher.java

@Override
public EntityIdentifier[] searchForEntities(String query, int method) throws GroupsException {
    boolean allowPartial = true;

    switch (method) {
    case IS:/*from w  w  w  .ja  va2s  .c  o m*/
        allowPartial = false;
        break;
    case STARTS_WITH:
        query = query + "%";
        break;
    case ENDS_WITH:
        query = "%" + query;
        break;
    case CONTAINS:
        query = "%" + query + "%";
        break;
    default:
        throw new GroupsException("Unknown search type");
    }

    // get the list of matching portlet definitions
    final List<IPortletDefinition> definitions = this.portletDefinitionRegistry.searchForPortlets(query,
            allowPartial);
    if (log.isDebugEnabled()) {
        log.debug("Found " + definitions.size() + " matching definitions for query " + query);
    }

    // initialize an appropriately-sized array of EntityIdentifiers
    final EntityIdentifier[] identifiers = new EntityIdentifier[definitions.size()];

    // add an identifier for each matching portlet
    for (final ListIterator<IPortletDefinition> defIter = definitions.listIterator(); defIter.hasNext();) {
        final IPortletDefinition definition = defIter.next();
        identifiers[defIter.previousIndex()] = new EntityIdentifier(
                definition.getPortletDefinitionId().getStringId(), this.getType());
    }

    return identifiers;

}

From source file:io.hops.transaction.context.INodeContext.java

private List<INode> findBatchWithLocalCacheCheck(INode.Finder inodeFinder, Object[] params)
        throws TransactionContextException, StorageException {
    final String[] names = (String[]) params[0];
    final long[] parentIds = (long[]) params[1];
    final long[] partitionIds = (long[]) params[2];

    List<String> namesRest = Lists.newArrayList();
    List<Long> parentIdsRest = Lists.newArrayList();
    List<Long> partitionIdsRest = Lists.newArrayList();
    List<Integer> unpopulatedIndeces = Lists.newArrayList();

    List<INode> result = new ArrayList<>(Collections.<INode>nCopies(names.length, null));

    for (int i = 0; i < names.length; i++) {
        final String nameParentKey = INode.nameParentKey(parentIds[i], names[i]);
        INode node = inodesNameParentIndex.get(nameParentKey);
        if (node != null) {
            result.set(i, node);/*from w  w  w .  j  a v a2 s. c  om*/
            hit(inodeFinder, node, "name", names[i], "parent_id", parentIds[i], "partition_id",
                    partitionIds[i]);
        } else {
            namesRest.add(names[i]);
            parentIdsRest.add(parentIds[i]);
            partitionIdsRest.add(partitionIds[i]);
            unpopulatedIndeces.add(i);
        }
    }

    if (unpopulatedIndeces.isEmpty()) {
        return result;
    }

    if (unpopulatedIndeces.size() == names.length) {
        return findBatch(inodeFinder, names, parentIds, partitionIds);
    } else {
        List<INode> batch = findBatch(inodeFinder, namesRest.toArray(new String[namesRest.size()]),
                Longs.toArray(parentIdsRest), Longs.toArray(partitionIdsRest));
        Iterator<INode> batchIterator = batch.listIterator();
        for (Integer i : unpopulatedIndeces) {
            if (batchIterator.hasNext()) {
                result.set(i, batchIterator.next());
            }
        }
        return result;
    }
}

From source file:com.caricah.iotracah.datastore.ignitecache.internal.impl.SubscriptionFilterHandler.java

public Observable<IotSubscriptionFilter> createTree(String partitionId, List<String> topicFilterTreeRoute) {

    return Observable.create(observer -> {

        try {/*w  ww.  ja v a  2s . com*/

            List<String> growingTitles = new ArrayList<>();
            LinkedList<Long> growingParentIds = new LinkedList<>();

            ListIterator<String> pathIterator = topicFilterTreeRoute.listIterator();

            while (pathIterator.hasNext()) {

                growingTitles.add(pathIterator.next());

                IotSubscriptionFilterKey iotSubscriptionFilterKey = keyFromList(partitionId, growingTitles);
                Observable<IotSubscriptionFilter> filterObservable = getByKeyWithDefault(
                        iotSubscriptionFilterKey, null);

                filterObservable.subscribe(internalSubscriptionFilter -> {

                    if (null == internalSubscriptionFilter) {
                        internalSubscriptionFilter = new IotSubscriptionFilter();
                        internalSubscriptionFilter.setPartitionId(partitionId);
                        internalSubscriptionFilter.setName(iotSubscriptionFilterKey.getName());
                        internalSubscriptionFilter.setId(getIdSequence().incrementAndGet());

                        if (growingParentIds.isEmpty()) {
                            internalSubscriptionFilter.setParentId(0l);
                        } else {
                            internalSubscriptionFilter.setParentId(growingParentIds.getLast());
                        }
                        save(iotSubscriptionFilterKey, internalSubscriptionFilter);
                    }

                    growingParentIds.add(internalSubscriptionFilter.getId());

                    if (growingTitles.size() == topicFilterTreeRoute.size())
                        observer.onNext(internalSubscriptionFilter);

                }, throwable -> {
                }, () -> {

                    if (!pathIterator.hasNext()) {

                        observer.onCompleted();

                    }

                });
            }

        } catch (Exception e) {
            observer.onError(e);
        }

    });
}

From source file:com.mirth.connect.server.userutil.DatabaseConnection.java

/**
 * Executes a prepared INSERT/UPDATE statement on the database and returns a CachedRowSet
 * containing any generated keys.// w  ww. java 2  s . com
 * 
 * @param expression
 *            The prepared statement to be executed.
 * @param parameters
 *            The parameters for the prepared statement.
 * @return A CachedRowSet containing any generated keys.
 * @throws SQLException
 */
public CachedRowSet executeUpdateAndGetGeneratedKeys(String expression, List<Object> parameters)
        throws SQLException {
    PreparedStatement statement = null;

    try {
        statement = connection.prepareStatement(expression, Statement.RETURN_GENERATED_KEYS);
        logger.debug("executing prepared statement:\n" + expression);

        ListIterator<Object> iterator = parameters.listIterator();

        while (iterator.hasNext()) {
            int index = iterator.nextIndex() + 1;
            Object value = iterator.next();
            logger.debug("adding parameter: index=" + index + ", value=" + value);
            statement.setObject(index, value);
        }

        statement.executeUpdate();
        CachedRowSet crs = new MirthCachedRowSet();
        crs.populate(statement.getGeneratedKeys());
        return crs;
    } catch (SQLException e) {
        throw e;
    } finally {
        DbUtils.closeQuietly(statement);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.web.jsptags.OptionsForPropertyTag.java

private List<Individual> removeIndividualsAlreadyInRange(List<Individual> indiviuals,
        List<ObjectPropertyStatement> stmts) {
    log.trace(//from ww  w.ja  v  a  2 s.c o  m
            "starting to check for duplicate range individuals in OptionsForPropertyTag.removeIndividualsAlreadyInRange() ...");
    HashSet<String> range = new HashSet<String>();

    for (ObjectPropertyStatement ops : stmts) {
        if (ops.getPropertyURI().equals(getPredicateUri()))
            range.add(ops.getObjectURI());
    }

    int removeCount = 0;
    ListIterator<Individual> it = indiviuals.listIterator();
    while (it.hasNext()) {
        Individual ind = it.next();
        if (range.contains(ind.getURI())) {
            it.remove();
            ++removeCount;
        }
    }
    log.trace("removed " + removeCount + " duplicate range individuals");
    return indiviuals;
}

From source file:com.projity.pm.graphic.model.transform.NodeCacheTransformer.java

private void recoverAssignments(List list, Map<GraphicNode, List<GraphicNode>> map) {
    GraphicNode current = null;// ww  w .j  a v a 2 s  .  c  o m
    for (ListIterator i = list.listIterator(); i.hasNext();) {
        current = (GraphicNode) i.next();
        if (map.containsKey(current)) {
            List<GraphicNode> ass = map.get(current);
            for (GraphicNode a : ass) {
                i.add(a);
            }
        }
    }
}

From source file:com.crearo.gpslogger.ui.fragments.display.GpsDetailedViewFragment.java

/**
 * Displays a human readable summary of the preferences chosen by the user
 * on the main form//from  ww w . j  a va2s.c o m
 */
private void showPreferencesAndMessages() {

    try {
        TextView txtLoggingTo = (TextView) rootView.findViewById(R.id.detailedview_loggingto_text);
        TextView txtFrequency = (TextView) rootView.findViewById(R.id.detailedview_frequency_text);
        TextView txtDistance = (TextView) rootView.findViewById(R.id.detailedview_distance_text);
        TextView txtAutoEmail = (TextView) rootView.findViewById(R.id.detailedview_autosend_text);

        List<FileLogger> loggers = FileLoggerFactory.getFileLoggers(getActivity().getApplicationContext());

        if (loggers.size() > 0) {

            ListIterator<FileLogger> li = loggers.listIterator();
            String logTo = li.next().getName();
            while (li.hasNext()) {
                logTo += ", " + li.next().getName();
            }

            if (preferenceHelper.shouldLogToNmea()) {
                logTo += ", NMEA";
            }

            txtLoggingTo.setText(logTo);

        } else {

            txtLoggingTo.setText(R.string.summary_loggingto_screen);

        }

        if (preferenceHelper.getMinimumLoggingInterval() > 0) {
            String descriptiveTime = Strings.getDescriptiveDurationString(
                    preferenceHelper.getMinimumLoggingInterval(), getActivity().getApplicationContext());

            txtFrequency.setText(descriptiveTime);
        } else {
            txtFrequency.setText(R.string.summary_freq_max);

        }

        if (preferenceHelper.getMinimumDistanceInterval() > 0) {
            txtDistance.setText(
                    Strings.getDistanceDisplay(getActivity(), preferenceHelper.getMinimumDistanceInterval(),
                            preferenceHelper.shouldDisplayImperialUnits()));
        } else {
            txtDistance.setText(R.string.summary_dist_regardless);
        }

        if (preferenceHelper.isAutoSendEnabled() && preferenceHelper.getAutoSendInterval() > 0) {
            String autoEmailDisplay = String.format(getString(R.string.autosend_frequency_display),
                    preferenceHelper.getAutoSendInterval());

            txtAutoEmail.setText(autoEmailDisplay);
        }

        showCurrentFileName(Session.getCurrentFileName(getActivity()));

        TextView txtTargets = (TextView) rootView.findViewById(R.id.detailedview_autosendtargets_text);

        if (preferenceHelper.isAutoSendEnabled()) {
            StringBuilder sb = new StringBuilder();
            if (FileSenderFactory.getEmailSender().isAutoSendAvailable()) {
                sb.append(getString(R.string.autoemail_title)).append("\n");
            }

            if (FileSenderFactory.getFtpSender().isAutoSendAvailable()) {
                sb.append(getString(R.string.autoftp_setup_title)).append("\n");
            }

            if (FileSenderFactory.getGoogleDriveSender().isAutoSendAvailable()) {
                sb.append(getString(R.string.gdocs_setup_title)).append("\n");
            }

            if (FileSenderFactory.getOsmSender().isAutoSendAvailable()) {
                sb.append(getString(R.string.osm_setup_title)).append("\n");
            }

            if (FileSenderFactory.getDropBoxSender().isAutoSendAvailable()) {
                sb.append(getString(R.string.dropbox_setup_title)).append("\n");
            }

            if (FileSenderFactory.getOpenGTSSender().isAutoSendAvailable()) {
                sb.append(getString(R.string.opengts_setup_title)).append("\n");
            }

            if (FileSenderFactory.getOwnCloudSender().isAutoSendAvailable()) {
                sb.append(getString(R.string.owncloud_setup_title)).append("\n");
            }

            txtTargets.setText(sb.toString());
        } else {
            txtTargets.setText("");
        }

    } catch (Exception ex) {
        LOG.error("showPreferencesAndMessages " + ex.getMessage(), ex);
    }

}

From source file:guineu.desktop.impl.helpsystem.GuineuHelpMap.java

/**
 * Determines the IDs related to this URL.
 *
 * @param URL/* www  . j a  v  a 2  s .com*/
 *            The URL to compare the Map IDs to.
 * @return Enumeration of Map.IDs
 */
@Override
public Enumeration<Object> getIDs(URL url) {
    String tmp = null;
    URL tmpURL = null;
    List<String> ids = new ArrayList<String>();
    for (Enumeration<String> e = getAllIDs(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        try {
            tmp = (String) lookup.get(key);
            tmpURL = new URL(tmp);
            if (url.sameFile(tmpURL) == true) {
                ids.add(key);
            }
        } catch (Exception ex) {
        }
    }
    return new FlatEnumeration(ids.listIterator(), helpset);
}