Example usage for java.util Set clear

List of usage examples for java.util Set clear

Introduction

In this page you can find the example usage for java.util Set clear.

Prototype

void clear();

Source Link

Document

Removes all of the elements from this set (optional operation).

Usage

From source file:nl.knaw.huygens.timbuctoo.tools.importer.neww.WomenWritersImporter.java

public void importAll() throws Exception {
    printBoxedText("Initialization");
    openImportLog("neww-log.txt");

    removeNonPersistentEntities(WWCollective.class);
    removeNonPersistentEntities(WWDocument.class);
    removeNonPersistentEntities(WWKeyword.class);
    removeNonPersistentEntities(WWPerson.class);
    removeNonPersistentEntities(WWRelation.class);

    printBoxedText("Import");

    importRelationTypes();// ww w. ja  va  2  s  .com
    setupRelationTypeDefs();

    System.out.println(".. Keywords");
    System.out.printf("Number = %6d%n%n", importKeywords());

    keywords = new KeywordConcordance(repository, change);
    keywords.handleFile(new File(inputDir, "neww-keywords.txt"), 0, false);

    System.out.println(".. Languages");
    System.out.printf("Number = %6d%n%n", importLanguages());

    System.out.println(".. Locations");
    System.out.printf("Number = %6d%n%n", importLocations());

    System.out.println(".. Collectives");
    System.out.printf("Number = %6d%n%n", importCollectives());

    System.out.println(".. Documents");
    System.out.printf("Source documents = %6d%n%n", importSourceDocuments());
    System.out.printf("Regular documents = %6d%n%n", importRegularDocuments());

    System.out.println(".. Persons");
    Set<String> collaboratorIds = collectCollaborators();
    System.out.printf("Number = %6d%n%n", importPersons(collaboratorIds));
    collaboratorIds.clear();

    System.out.printf("nUnknown    %5d%n", nUnknown);
    System.out.printf("nArchetype  %5d%n", nArchetype);
    System.out.printf("nAuthor     %5d%n", nAuthor);
    System.out.printf("nPseudonym  %5d%n", nPseudonym);
    System.out.printf("nDuplicates %5d%n", nDuplicates);

    System.out.println(".. Relations");
    importRelations();
    System.out.printf("Number of missing relation types = %6d%n", missingRelationTypes);
    System.out.printf("Number of unstored relations     = %6d%n", unstoredRelations);
    System.out.printf("Number of duplicate relations    = %6d%n", getDuplicateRelationCount());

    printBoxedText("Indexing");

    indexEntities(WWCollective.class);
    indexEntities(WWDocument.class);
    indexEntities(WWKeyword.class);
    indexEntities(WWLanguage.class);
    indexEntities(WWPerson.class);
    indexEntities(WWLocation.class);
    indexEntities(WWRelation.class);

    displayStatus();
    displayErrorSummary();
    closeImportLog();
}

From source file:com.android.contacts.common.ContactPhotoManager.java

/**
 * Populates an array of photo IDs that need to be loaded. Also decodes bitmaps that we have
 * already loaded// ww  w .  j a v  a 2s . c  om
 */
private void obtainPhotoIdsAndUrisToLoad(Set<Long> photoIds, Set<String> photoIdsAsStrings, Set<Request> uris) {
    photoIds.clear();
    photoIdsAsStrings.clear();
    uris.clear();

    boolean jpegsDecoded = false;

    /*
     * Since the call is made from the loader thread, the map could be
     * changing during the iteration. That's not really a problem:
     * ConcurrentHashMap will allow those changes to happen without throwing
     * exceptions. Since we may miss some requests in the situation of
     * concurrent change, we will need to check the map again once loading
     * is complete.
     */
    Iterator<Request> iterator = mPendingRequests.values().iterator();
    while (iterator.hasNext()) {
        Request request = iterator.next();
        final BitmapHolder holder = mBitmapHolderCache.get(request.getKey());
        if (holder == BITMAP_UNAVAILABLE) {
            continue;
        }
        if (holder != null && holder.bytes != null && holder.fresh
                && (holder.bitmapRef == null || holder.bitmapRef.get() == null)) {
            // This was previously loaded but we don't currently have the inflated Bitmap
            inflateBitmap(holder, request.getRequestedExtent());
            jpegsDecoded = true;
        } else {
            if (holder == null || !holder.fresh) {
                if (request.isUriRequest()) {
                    uris.add(request);
                } else {
                    photoIds.add(request.getId());
                    photoIdsAsStrings.add(String.valueOf(request.mId));
                }
            }
        }
    }

    if (jpegsDecoded)
        mMainThreadHandler.sendEmptyMessage(MESSAGE_PHOTOS_LOADED);
}

From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.ShardSyncerTest.java

/**
 * Test isCandidateForCleanup//from   w w w. j a v  a 2s. c om
 * 
 * @throws KinesisClientLibIOException
 */
@Test
public final void testIsCandidateForCleanup() throws KinesisClientLibIOException {
    String parentShardId = "shardId-0000";
    String adjacentParentShardId = "shardId-0001";
    String shardId = "shardId-0002";
    KinesisClientLease lease = newLease(shardId);
    List<String> parentShardIds = new ArrayList<>();
    parentShardIds.add(parentShardId);
    parentShardIds.add(adjacentParentShardId);
    lease.setParentShardIds(parentShardIds);
    Set<String> currentKinesisShardIds = new HashSet<>();

    currentKinesisShardIds.add(shardId);
    Assert.assertFalse(ShardSyncer.isCandidateForCleanup(lease, currentKinesisShardIds));

    currentKinesisShardIds.clear();
    Assert.assertTrue(ShardSyncer.isCandidateForCleanup(lease, currentKinesisShardIds));

    currentKinesisShardIds.add(parentShardId);
    // Assert.assertFalse(ShardSyncer.isCandidateForCleanup(lease, currentKinesisShardIds));

    currentKinesisShardIds.clear();
    Assert.assertTrue(ShardSyncer.isCandidateForCleanup(lease, currentKinesisShardIds));

    currentKinesisShardIds.add(adjacentParentShardId);
    // Assert.assertFalse(ShardSyncer.isCandidateForCleanup(lease, currentKinesisShardIds));
    currentKinesisShardIds.add(parentShardId);
    // Assert.assertFalse(ShardSyncer.isCandidateForCleanup(lease, currentKinesisShardIds));
    currentKinesisShardIds.add(shardId);
    Assert.assertFalse(ShardSyncer.isCandidateForCleanup(lease, currentKinesisShardIds));
}

From source file:tools.xor.logic.DefaultUpdate4Set.java

public void testCase24() {
    C = taskDao.findById(C.getId());//ww  w.j  a  va 2 s .  c  o m
    B = taskDao.findById(B.getId());
    Set<Task> children = new HashSet<Task>();
    children.add(C);
    children.add(B);

    // Setup the bi-directional link
    A = taskDao.findById(A.getId());
    A.setTaskChildren(children);
    C.setTaskParent(A);
    B.setTaskParent(A);
    taskDao.saveOrUpdate(A);

    A = (Task) aggregateService.read(A, getSettings());

    assert (A.getTaskChildren().size() == 2);
    Iterator<Task> iter = A.getTaskChildren().iterator();
    Task child1 = iter.next();
    Task child2 = iter.next();
    if (child1.getName().equals(B_NAME)) {
        B = child1;
        C = child2;
    } else {
        C = child1;
        B = child2;
    }
    assert (B.getName().equals(B_NAME) && C.getName().equals(C_NAME));

    children = A.getTaskChildren();
    children.clear();
    children.add(B);
    children.add(D);
    A.setAlternateTask(C);
    C.setTaskParent(null);
    B.setTaskParent(A);
    D.setTaskParent(A);

    Settings settings = getSettings();
    settings.setInterceptor(new Interceptor() {
        // check the number of actions in each object
        private void checkNumber(BusinessObject dataObject, List<Executable> actions) {
            Task task = (Task) dataObject.getInstance();
            if (task.getName().equals(A_NAME)) {
                assert (actions.size() == 1); // SetUpdateAction
                assert (SetUpdateAction.class.isAssignableFrom(actions.get(0).getClass()));
            } else
                assert (actions.size() == 2);
        }

        @Override
        public void preBiDirActionStage(Map<PropertyKey, List<Executable>> actions) {
            // check the action queue to see if the correct number of actions are present
            assert (actions.size() == 3);

            for (Map.Entry<PropertyKey, List<Executable>> entry : actions.entrySet())
                checkNumber(entry.getKey().getDataObject(), entry.getValue());
        }
    });
    A = (Task) aggregateService.update(A, settings);

    A = taskDao.findById(A.getId());
    B = taskDao.findById(B.getId());
    D = taskDao.findById(D.getId());

    A = (Task) aggregateService.read(A, getSettings());
    B = (Task) aggregateService.read(B, getSettings());
    D = (Task) aggregateService.read(D, getSettings());

    assert (A.getTaskChildren() != null && A.getTaskChildren().size() == 2);
}

From source file:tools.xor.logic.DefaultUpdate4Set.java

public void testCase23() {
    C = taskDao.findById(C.getId());/* www .  ja  v  a2s.  c  o  m*/
    B = taskDao.findById(B.getId());
    Set<Task> children = new HashSet<Task>();
    children.add(C);
    children.add(B);

    // Setup the bi-directional link
    A = taskDao.findById(A.getId());
    A.setTaskChildren(children);
    C.setTaskParent(A);
    B.setTaskParent(A);
    taskDao.saveOrUpdate(A);

    A = (Task) aggregateService.read(A, getSettings());

    assert (A.getTaskChildren().size() == 2);
    Iterator<Task> iter = A.getTaskChildren().iterator();
    Task child1 = iter.next();
    Task child2 = iter.next();
    if (child1.getName().equals(B_NAME)) {
        B = child1;
        C = child2;
    } else {
        C = child1;
        B = child2;
    }
    assert (B.getName().equals(B_NAME) && C.getName().equals(C_NAME));

    children = A.getTaskChildren();
    children.clear();
    children.add(D);
    A.setAlternateTask(C);
    D.setAlternateTask(B);
    C.setTaskParent(null);
    B.setTaskParent(null);
    D.setTaskParent(A);

    Settings settings = getSettings();
    settings.setInterceptor(new Interceptor() {
        // check the number of actions in each object
        private void checkNumber(BusinessObject dataObject, List<Executable> actions) {
            Task task = (Task) dataObject.getInstance();
            if (task.getName().equals(A_NAME)) {
                assert (actions.size() == 1); // SetUpdateAction
                assert (SetUpdateAction.class.isAssignableFrom(actions.get(0).getClass()));
            } else
                assert (actions.size() == 2);
        }

        @Override
        public void preBiDirActionStage(Map<PropertyKey, List<Executable>> actions) {
            // check the action queue to see if the correct number of actions are present
            assert (actions.size() == 4);

            for (Map.Entry<PropertyKey, List<Executable>> entry : actions.entrySet())
                checkNumber(entry.getKey().getDataObject(), entry.getValue());
        }
    });
    A = (Task) aggregateService.update(A, settings);

    A = taskDao.findById(A.getId());
    B = taskDao.findById(B.getId());
    D = taskDao.findById(D.getId());

    A = (Task) aggregateService.read(A, getSettings());
    B = (Task) aggregateService.read(B, getSettings());
    D = (Task) aggregateService.read(D, getSettings());

    assert (A.getTaskChildren() != null && A.getTaskChildren().size() == 1);
    assert (D.getId() == A.getTaskChildren().iterator().next().getId());
}

From source file:io.ecarf.core.cloud.task.processor.reason.phase1.DoReasonTask5.java

/**
 * /* w w w.  j  av a  2 s  . com*/
 * @param term
 * @param select
 * @param schemaTriples
 * @param rows
 * @param table
 * @param writer
 * @return
 * @throws IOException
 */
private int inferAndSaveTriplesToFile(Term term, List<String> select, Set<Triple> schemaTriples,
        BigInteger rows, String table, PrintWriter writer) throws IOException {

    int inferredTriples = 0;
    int failedTriples = 0;

    // loop through the instance triples probably stored in a file and generate all the triples matching the schema triples set
    try (BufferedReader r = new BufferedReader(new FileReader(term.getFilename()), Constants.GZIP_BUF_SIZE)) {

        Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(r);

        // records will contain lots of duplicates
        Set<String> inferredAlready = new HashSet<String>();

        try {

            for (CSVRecord record : records) {

                String values = ((select.size() == 1) ? record.get(0) : StringUtils.join(record.values(), ','));

                if (!inferredAlready.contains(values)) {
                    inferredAlready.add(values);

                    NTriple instanceTriple = new NTriple();

                    if (select.size() == 1) {
                        instanceTriple.set(select.get(0), record.get(0));
                    } else {

                        instanceTriple.set(select, record.values());
                    }

                    for (Triple schemaTriple : schemaTriples) {
                        Rule rule = GenericRule.getRule(schemaTriple);
                        Triple inferredTriple = rule.head(schemaTriple, instanceTriple);

                        if (inferredTriple != null) {
                            writer.println(inferredTriple.toCsv());
                            inferredTriples++;
                        }
                    }

                    // this is just to avoid any memory issues
                    if (inferredAlready.size() > MAX_CACHE) {
                        inferredAlready.clear();
                        log.info("Cleared cache of inferred terms");
                    }
                } else {
                    this.duplicates++;
                }

            }
        } catch (Exception e) {
            log.error("Failed to parse selected terms", e);
            failedTriples++;
        }
    }

    //inferredFiles.add(inferredTriplesFile);
    log.info("\nSelect Triples: " + rows + ", Inferred: " + inferredTriples + ", Triples for term: " + term
            + ", Failed Triples: " + failedTriples);

    return inferredTriples;
}

From source file:org.apache.sentry.provider.db.service.thrift.SentryPolicyStoreProcessor.java

@Override
public TListSentryRolesResponse list_sentry_roles_by_group(TListSentryRolesRequest request) throws TException {
    final Timer.Context timerContext = sentryMetrics.listRolesByGroupTimer.time();
    TListSentryRolesResponse response = new TListSentryRolesResponse();
    TSentryResponseStatus status;//w w w.j av a  2 s.  com
    Set<TSentryRole> roleSet = new HashSet<TSentryRole>();
    String subject = request.getRequestorUserName();
    boolean checkAllGroups = false;
    try {
        validateClientVersion(request.getProtocol_version());
        Set<String> groups = getRequestorGroups(subject);
        // Don't check admin permissions for listing requestor's own roles
        if (AccessConstants.ALL.equalsIgnoreCase(request.getGroupName())) {
            checkAllGroups = true;
        } else {
            boolean admin = inAdminGroups(groups);
            //Only admin users can list all roles in the system ( groupname = null)
            //Non admin users are only allowed to list only groups which they belong to
            if (!admin && (request.getGroupName() == null || !groups.contains(request.getGroupName()))) {
                throw new SentryAccessDeniedException("Access denied to " + subject);
            } else {
                groups.clear();
                groups.add(request.getGroupName());
            }
        }
        roleSet = sentryStore.getTSentryRolesByGroupName(groups, checkAllGroups);
        response.setRoles(roleSet);
        response.setStatus(Status.OK());
    } catch (SentryNoSuchObjectException e) {
        response.setRoles(roleSet);
        String msg = "Request: " + request + " couldn't be completed, message: " + e.getMessage();
        LOGGER.error(msg, e);
        response.setStatus(Status.NoSuchObject(msg, e));
    } catch (SentryAccessDeniedException e) {
        LOGGER.error(e.getMessage(), e);
        response.setStatus(Status.AccessDenied(e.getMessage(), e));
    } catch (SentryThriftAPIMismatchException e) {
        LOGGER.error(e.getMessage(), e);
        response.setStatus(Status.THRIFT_VERSION_MISMATCH(e.getMessage(), e));
    } catch (Exception e) {
        String msg = "Unknown error for request: " + request + ", message: " + e.getMessage();
        LOGGER.error(msg, e);
        response.setStatus(Status.RuntimeError(msg, e));
    } finally {
        timerContext.stop();
    }
    return response;
}

From source file:com.kalessil.phpStorm.phpInspectionsEA.inspectors.apiUsage.UnSafeIsSetOverArrayInspector.java

@Override
@NotNull// w w  w .  j ava 2s.  c om
public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, boolean isOnTheFly) {
    return new BasePhpElementVisitor() {
        @Override
        public void visitPhpIsset(@NotNull PhpIsset issetExpression) {
            /*
             * if no parameters, we don't check;
             * if multiple parameters, perhaps if-inspection fulfilled and isset's were merged
             *
             * TODO: still needs analysis regarding concatenations in indexes
             */
            final PhpExpression[] arguments = issetExpression.getVariables();
            if (arguments.length != 1) {
                return;
            }

            /* gather context information */
            PsiElement issetParent = issetExpression.getParent();
            boolean issetInverted = false;
            if (issetParent instanceof UnaryExpression) {
                final PsiElement operator = ((UnaryExpression) issetParent).getOperation();
                if (OpenapiTypesUtil.is(operator, PhpTokenTypes.opNOT)) {
                    issetInverted = true;
                    issetParent = issetParent.getParent();
                }
            }
            boolean isResultStored = (issetParent instanceof AssignmentExpression
                    || issetParent instanceof PhpReturn);

            /* false-positives:  ternaries using isset-or-null semantics, there array_key_exist can introduce bugs */
            final PsiElement conditionCandidate = issetInverted ? issetExpression.getParent() : issetExpression;
            boolean isTernaryCondition = issetParent instanceof TernaryExpression
                    && conditionCandidate == ((TernaryExpression) issetParent).getCondition();
            if (isTernaryCondition) {
                final TernaryExpression ternary = (TernaryExpression) issetParent;
                final PsiElement nullCandidate = issetInverted ? ternary.getTrueVariant()
                        : ternary.getFalseVariant();
                if (PhpLanguageUtil.isNull(nullCandidate)) {
                    return;
                }
            }

            /* do analyze  */
            final PsiElement argument = ExpressionSemanticUtil.getExpressionTroughParenthesis(arguments[0]);
            if (argument == null) {
                return;
            }
            /* false positives: variables in template/global context - too unreliable */
            if (argument instanceof Variable && ExpressionSemanticUtil.getBlockScope(argument) == null) {
                return;
            }

            if (!(argument instanceof ArrayAccessExpression)) {
                if (argument instanceof FieldReference) {
                    /* if field is not resolved, it's probably dynamic and isset has a purpose */
                    final PsiReference referencedField = argument.getReference();
                    final PsiElement resolvedField = referencedField == null ? null
                            : OpenapiResolveUtil.resolveReference(referencedField);
                    if (resolvedField == null
                            || !(ExpressionSemanticUtil.getBlockScope(resolvedField) instanceof PhpClass)) {
                        return;
                    }
                }

                if (SUGGEST_TO_USE_NULL_COMPARISON) {
                    /* false-positives: finally, perhaps fallback to initialization in try */
                    if (PsiTreeUtil.getParentOfType(issetExpression, Finally.class) == null) {
                        final List<String> fragments = Arrays.asList(argument.getText(),
                                issetInverted ? "===" : "!==", "null");
                        if (!ComparisonStyle.isRegular()) {
                            Collections.reverse(fragments);
                        }
                        final String replacement = String.join(" ", fragments);
                        holder.registerProblem(issetInverted ? issetExpression.getParent() : issetExpression,
                                String.format(patternUseNullComparison, replacement),
                                ProblemHighlightType.WEAK_WARNING, new CompareToNullFix(replacement));
                    }
                }
                return;
            }

            /* TODO: has method/function reference as index */
            if (REPORT_CONCATENATION_IN_INDEXES && !isResultStored
                    && this.hasConcatenationAsIndex((ArrayAccessExpression) argument)) {
                holder.registerProblem(argument, messageConcatenationInIndex);
                return;
            }

            if (SUGGEST_TO_USE_ARRAY_KEY_EXISTS && !isArrayAccess((ArrayAccessExpression) argument)) {
                holder.registerProblem(argument, messageUseArrayKeyExists, ProblemHighlightType.WEAK_WARNING);
            }
        }

        /* checks if any of indexes is concatenation expression */
        /* TODO: iterator for array access expression */
        private boolean hasConcatenationAsIndex(@NotNull ArrayAccessExpression expression) {
            PsiElement expressionToInspect = expression;
            while (expressionToInspect instanceof ArrayAccessExpression) {
                final ArrayIndex index = ((ArrayAccessExpression) expressionToInspect).getIndex();
                if (index != null && index.getValue() instanceof BinaryExpression) {
                    final PsiElement operation = ((BinaryExpression) index.getValue()).getOperation();
                    if (operation != null && operation.getNode().getElementType() == PhpTokenTypes.opCONCAT) {
                        return true;
                    }
                }

                expressionToInspect = expressionToInspect.getParent();
            }

            return false;
        }

        // TODO: partially duplicates semanticalAnalysis.OffsetOperationsInspector.isContainerSupportsArrayAccess()
        private boolean isArrayAccess(@NotNull ArrayAccessExpression expression) {
            /* ok JB parses `$var[]= ...` always as array, lets make it working properly and report them later */
            final PsiElement container = expression.getValue();
            if (!(container instanceof PhpTypedElement)) {
                return false;
            }

            final Set<String> containerTypes = new HashSet<>();
            final PhpType resolved = OpenapiResolveUtil.resolveType((PhpTypedElement) container,
                    container.getProject());
            if (resolved != null) {
                resolved.filterUnknown().getTypes().forEach(t -> containerTypes.add(Types.getType(t)));
            }
            /* failed to resolve, don't try to guess anything */
            if (containerTypes.isEmpty()) {
                return false;
            }

            boolean supportsOffsets = false;
            for (final String typeToCheck : containerTypes) {
                /* assume is just null-ble declaration or we shall just rust to mixed */
                if (typeToCheck.equals(Types.strNull)) {
                    continue;
                }
                if (typeToCheck.equals(Types.strMixed)) {
                    supportsOffsets = true;
                    continue;
                }

                /* some of possible types are scalars, what's wrong */
                if (!StringUtils.isEmpty(typeToCheck) && typeToCheck.charAt(0) != '\\') {
                    supportsOffsets = false;
                    break;
                }

                /* assume class has what is needed, OffsetOperationsInspector should report if not */
                supportsOffsets = true;
            }
            containerTypes.clear();

            return supportsOffsets;
        }
    };
}

From source file:net.adamcin.recap.impl.RecapSessionImpl.java

/**
 * The recursive copy function// w w  w  .j  a va  2  s .  c  om
 * @param src existing source node
 * @param dstParent existing destination parent node
 * @param dstName name of destination node
 * @param recursive
 * @throws RecapSessionException
 * @throws RepositoryException
 */
private void copy(Node src, Node dstParent, String dstName, boolean recursive)
        throws RecapSessionException, RepositoryException {

    if (interrupter.isInterrupted()) {
        throw new RecapSessionException("RecapSession interrupted.");
    }

    String path = src.getPath();
    String dstPath = dstParent.getPath() + "/" + dstName;

    boolean useSysView = src.getDefinition().isProtected();
    boolean isNew = false;
    boolean overwrite = this.options.isUpdate();
    boolean included = this.options.getFilter().includesPath(path);

    getTargetSession().disableAutoSave();

    ++totalNodes;
    Node dst;
    if (dstParent.hasNode(dstName)) {
        dst = dstParent.getNode(dstName);
        if (!included) {
            trackPath(RecapProgressListener.PathAction.IGNORE, dstPath);
        } else if (overwrite) {
            if ((this.options.isOnlyNewer()) && (dstName.equals(JcrConstants.JCR_CONTENT))) {
                if (isNewer(src, dst)) {
                    trackPath(RecapProgressListener.PathAction.UPDATE, dstPath);
                } else {
                    overwrite = false;
                    recursive = false;
                    trackPath(RecapProgressListener.PathAction.NO_ACTION, dstPath);
                }
            } else {
                trackPath(RecapProgressListener.PathAction.UPDATE, dstPath);
            }

            if (useSysView) {
                dst = sysCopy(src, dstParent, dstName);
            }
        } else {
            trackPath(RecapProgressListener.PathAction.NO_ACTION, dstPath);
        }
    } else {
        try {
            if (included && useSysView) {
                dst = sysCopy(src, dstParent, dstName);
            } else {
                dst = dstParent.addNode(dstName, src.getPrimaryNodeType().getName());
            }
            trackPath(RecapProgressListener.PathAction.ADD, dstPath);
            isNew = true;
        } catch (RepositoryException e) {
            LOGGER.warn("Error while adding node {} (ignored): {}", dstPath, e.toString());
            trackError(dstPath, e);
            return;
        }
    }

    if (included && useSysView) {
        trackTree(dst, isNew);
    } else {
        Set<String> names = new HashSet<String>();
        if (included && ((overwrite) || (isNew))) {
            if (!isNew) {
                for (NodeType nt : dst.getMixinNodeTypes()) {
                    names.add(nt.getName());
                }

                for (NodeType nt : src.getMixinNodeTypes()) {
                    String mixName = checkNameSpace(nt.getName());
                    if (!names.remove(mixName)) {
                        dst.addMixin(nt.getName());
                    }
                }

                for (String mix : names) {
                    dst.removeMixin(mix);
                }
            } else {
                for (NodeType nt : src.getMixinNodeTypes()) {
                    dst.addMixin(checkNameSpace(nt.getName()));
                }
            }

            names.clear();
            if (!isNew) {
                PropertyIterator iter = dst.getProperties();
                while (iter.hasNext()) {
                    names.add(checkNameSpace(iter.nextProperty().getName()));
                }
            }
            PropertyIterator iter = src.getProperties();
            while (iter.hasNext()) {
                Property p = iter.nextProperty();
                String pName = checkNameSpace(p.getName());
                names.remove(pName);

                if (p.getDefinition().isProtected()) {
                    continue;
                }
                if (dst.hasProperty(pName)) {
                    dst.getProperty(pName).remove();
                }
                if (p.getDefinition().isMultiple()) {
                    Value[] vs = p.getValues();
                    dst.setProperty(pName, vs);
                    for (long s : p.getLengths()) {
                        this.totalSize += s;
                        this.currentSize += s;
                    }
                } else {
                    Value v = p.getValue();
                    dst.setProperty(pName, v);
                    long s = p.getLength();
                    this.totalSize += s;
                    this.currentSize += s;
                }
            }

            for (String pName : names) {
                try {
                    dst.getProperty(pName).remove();
                } catch (RepositoryException e) {
                    LOGGER.warn("[copy] failed to remove property {} from node {}", pName, path);
                }
            }
        }

        // re-enable auto-save before recursion
        getTargetSession().enableAutoSave();

        if (recursive) {
            names.clear();
            if ((overwrite) && (!isNew)) {
                NodeIterator niter = dst.getNodes();
                while (niter.hasNext()) {
                    names.add(checkNameSpace(niter.nextNode().getName()));
                }
            }
            NodeIterator niter = src.getNodes();
            while (niter.hasNext()) {
                Node child = niter.nextNode();
                String cName = checkNameSpace(child.getName());
                names.remove(cName);
                copy(child, dst, cName, true);
            }

            if (!options.isNoDelete()) {
                for (String name : names) {
                    try {
                        Node cNode = dst.getNode(name);
                        cNode.remove();
                    } catch (RepositoryException e) {
                        LOGGER.warn("[copy] failed to delete existing node in dst that does not exist in src",
                                e);
                    }
                }
            }

            if (options.isKeepOrder() && !isNew && supportsOrdering(src) && supportsOrdering(dst)) {
                OrderableNodesList srcChildren = new OrderableNodesList(src);
                OrderableNodesList dstChildren = new OrderableNodesList(dst);
                while (!ensureOrder(srcChildren, dstChildren)) {
                    //reorder children
                }
            }
        }
    }
}

From source file:com.googlecode.jsonrpc4j.JsonRpcServer.java

/**
 * Finds the {@link Method} from the supplied {@link Set} that
 * best matches the rest of the arguments supplied and returns
 * it as a {@link MethodAndArgs} class.//from   ww  w .  j a va  2 s .  c  om
 *
 * @param methods the {@link Method}s
 * @param paramCount the number of expect parameters
 * @param paramNodes the parameters for matching types
 * @return the {@link MethodAndArgs}
 */
private MethodAndArgs findBestMethodUsingParamIndexes(Set<Method> methods, int paramCount,
        ArrayNode paramNodes) {

    // get param count
    int numParams = paramNodes != null && !paramNodes.isNull() ? paramNodes.size() : 0;

    // determine param count
    int bestParamNumDiff = Integer.MAX_VALUE;
    Set<Method> matchedMethods = new HashSet<Method>();

    // check every method
    for (Method method : methods) {

        // get parameter types
        Class<?>[] paramTypes = method.getParameterTypes();
        int paramNumDiff = paramTypes.length - paramCount;

        // we've already found a better match
        if (Math.abs(paramNumDiff) > Math.abs(bestParamNumDiff)) {
            continue;

            // we don't allow extra params
        } else if (!allowExtraParams && paramNumDiff < 0 || !allowLessParams && paramNumDiff > 0) {
            continue;

            // check the parameters
        } else {
            if (Math.abs(paramNumDiff) < Math.abs(bestParamNumDiff)) {
                matchedMethods.clear();
            }
            matchedMethods.add(method);
            bestParamNumDiff = paramNumDiff;
            continue;
        }
    }

    // bail early
    if (matchedMethods.isEmpty()) {
        return null;
    }

    // now narrow it down to the best method
    // based on argument types
    Method bestMethod = null;
    if (matchedMethods.size() == 1 || numParams == 0) {
        bestMethod = matchedMethods.iterator().next();

    } else {

        // check the matching methods for
        // matching parameter types
        int mostMatches = -1;
        for (Method method : matchedMethods) {
            List<Class<?>> parameterTypes = getParameterTypes(method);
            int numMatches = 0;
            for (int i = 0; i < parameterTypes.size() && i < numParams; i++) {
                if (isMatchingType(paramNodes.get(i), parameterTypes.get(i))) {
                    numMatches++;
                }
            }
            if (numMatches > mostMatches) {
                mostMatches = numMatches;
                bestMethod = method;
            }
        }
    }

    // create return
    MethodAndArgs ret = new MethodAndArgs();
    ret.method = bestMethod;

    // now fill arguments
    int numParameters = bestMethod.getParameterTypes().length;
    for (int i = 0; i < numParameters; i++) {
        if (i < numParams) {
            ret.arguments.add(paramNodes.get(i));
        } else {
            ret.arguments.add(NullNode.getInstance());
        }
    }

    // return the method
    return ret;
}