Java Code Examples for java.util.SortedSet#iterator()

The following examples show how to use java.util.SortedSet#iterator() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public void setOptions(SortedSet<QuestionOption> options) {
	this.options = options;
	if (options !=null){
	short i= 1;
	Iterator<QuestionOption> it;
	it = options.iterator();
	while (it.hasNext()) {
		QuestionOption questionOption  = it.next();
		questionOption.setOrder(i);
		optionsList.add(questionOption);
		optionsList2.add(questionOption);
		i++;
	}
	}
	
}
 
Example 2
public static int compareTo(Set a, Set b) {
  int lastComparison = compareTo(a.size(), b.size());
  if (lastComparison != 0) {
    return lastComparison;
  }
  SortedSet sortedA = new TreeSet(comparator);
  sortedA.addAll(a);
  SortedSet sortedB = new TreeSet(comparator);
  sortedB.addAll(b);

  Iterator iterA = sortedA.iterator();
  Iterator iterB = sortedB.iterator();

  // Compare each item.
  while (iterA.hasNext() && iterB.hasNext()) {
    lastComparison = comparator.compare(iterA.next(), iterB.next());
    if (lastComparison != 0) {
      return lastComparison;
    }
  }

  return 0;
}
 
Example 3
public void testSubSetContents2() {
    ConcurrentSkipListSet set = set5();
    SortedSet sm = set.subSet(two, three);
    assertEquals(1, sm.size());
    assertEquals(two, sm.first());
    assertEquals(two, sm.last());
    assertFalse(sm.contains(one));
    assertTrue(sm.contains(two));
    assertFalse(sm.contains(three));
    assertFalse(sm.contains(four));
    assertFalse(sm.contains(five));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    assertFalse(i.hasNext());
    Iterator j = sm.iterator();
    j.next();
    j.remove();
    assertFalse(set.contains(two));
    assertEquals(4, set.size());
    assertEquals(0, sm.size());
    assertTrue(sm.isEmpty());
    assertFalse(sm.remove(three));
    assertEquals(4, set.size());
}
 
Example 4
public void testDescendingSubSetContents2() {
    NavigableSet set = dset5();
    SortedSet sm = set.subSet(m2, m3);
    assertEquals(1, sm.size());
    assertEquals(m2, sm.first());
    assertEquals(m2, sm.last());
    assertFalse(sm.contains(m1));
    assertTrue(sm.contains(m2));
    assertFalse(sm.contains(m3));
    assertFalse(sm.contains(m4));
    assertFalse(sm.contains(m5));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(m2, k);
    assertFalse(i.hasNext());
    Iterator j = sm.iterator();
    j.next();
    j.remove();
    assertFalse(set.contains(m2));
    assertEquals(4, set.size());
    assertEquals(0, sm.size());
    assertTrue(sm.isEmpty());
    assertFalse(sm.remove(m3));
    assertEquals(4, set.size());
}
 
Example 5
public void testSubSetContents2() {
    NavigableSet set = set5();
    SortedSet sm = set.subSet(two, three);
    assertEquals(1, sm.size());
    assertEquals(two, sm.first());
    assertEquals(two, sm.last());
    assertFalse(sm.contains(one));
    assertTrue(sm.contains(two));
    assertFalse(sm.contains(three));
    assertFalse(sm.contains(four));
    assertFalse(sm.contains(five));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    assertFalse(i.hasNext());
    Iterator j = sm.iterator();
    j.next();
    j.remove();
    assertFalse(set.contains(two));
    assertEquals(4, set.size());
    assertEquals(0, sm.size());
    assertTrue(sm.isEmpty());
    assertFalse(sm.remove(three));
    assertEquals(4, set.size());
}
 
Example 6
private static String normal(Set<Dependency> deps) {
    SortedSet<String> s = new TreeSet<String>(); // Set<String>
    Iterator<Dependency> it = deps.iterator();
    while (it.hasNext()) {
        Dependency d = it.next();
        s.add(dep2String(d));
    }
    StringBuilder b = new StringBuilder();
    Iterator<String> it2 = s.iterator();
    while (it2.hasNext()) {
        b.append(it2.next());
        if (it2.hasNext()) {
            b.append(", ");
        }
    }
    return b.toString();
}
 
Example 7
public void testSubSetContents2() {
    NavigableSet set = set5();
    SortedSet sm = set.subSet(two, three);
    assertEquals(1, sm.size());
    assertEquals(two, sm.first());
    assertEquals(two, sm.last());
    assertFalse(sm.contains(one));
    assertTrue(sm.contains(two));
    assertFalse(sm.contains(three));
    assertFalse(sm.contains(four));
    assertFalse(sm.contains(five));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    assertFalse(i.hasNext());
    Iterator j = sm.iterator();
    j.next();
    j.remove();
    assertFalse(set.contains(two));
    assertEquals(4, set.size());
    assertEquals(0, sm.size());
    assertTrue(sm.isEmpty());
    assertFalse(sm.remove(three));
    assertEquals(4, set.size());
}
 
Example 8
@Override
protected final Outcome resolve_XALOAD_ResolvedNonconcrete(ArrayAccessInfo arrayAccessInfo, SortedSet<DecisionAlternative_XALOAD> result)
throws DecisionException {
    final Outcome retVal = super.resolve_XALOAD_ResolvedNonconcrete(arrayAccessInfo, result);
    if (this.guiding) {
        final Iterator<DecisionAlternative_XALOAD> it = result.iterator();
        while (it.hasNext()) {
            final DecisionAlternative_XALOAD da = it.next();
            final Primitive valueInConcreteState = this.jvm.eval_XALOAD(da);
            if (valueInConcreteState != null && valueInConcreteState.surelyFalse()) {
                it.remove();
            }
        }
    }
    return retVal;
}
 
Example 9
/**
 * tailSet returns set with keys in requested range
 */
public void testTailSetContents() {
    ConcurrentSkipListSet set = set5();
    SortedSet sm = set.tailSet(two);
    assertFalse(sm.contains(one));
    assertTrue(sm.contains(two));
    assertTrue(sm.contains(three));
    assertTrue(sm.contains(four));
    assertTrue(sm.contains(five));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    k = (Integer)(i.next());
    assertEquals(three, k);
    k = (Integer)(i.next());
    assertEquals(four, k);
    k = (Integer)(i.next());
    assertEquals(five, k);
    assertFalse(i.hasNext());

    SortedSet ssm = sm.tailSet(four);
    assertEquals(four, ssm.first());
    assertEquals(five, ssm.last());
    assertTrue(ssm.remove(four));
    assertEquals(1, ssm.size());
    assertEquals(3, sm.size());
    assertEquals(4, set.size());
}
 
Example 10
/**
 * tailSet returns set with keys in requested range
 */
public void testDescendingTailSetContents() {
    NavigableSet set = dset5();
    SortedSet sm = set.tailSet(m2);
    assertFalse(sm.contains(m1));
    assertTrue(sm.contains(m2));
    assertTrue(sm.contains(m3));
    assertTrue(sm.contains(m4));
    assertTrue(sm.contains(m5));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(m2, k);
    k = (Integer)(i.next());
    assertEquals(m3, k);
    k = (Integer)(i.next());
    assertEquals(m4, k);
    k = (Integer)(i.next());
    assertEquals(m5, k);
    assertFalse(i.hasNext());

    SortedSet ssm = sm.tailSet(m4);
    assertEquals(m4, ssm.first());
    assertEquals(m5, ssm.last());
    assertTrue(ssm.remove(m4));
    assertEquals(1, ssm.size());
    assertEquals(3, sm.size());
    assertEquals(4, set.size());
}
 
Example 11
private void dumpPerFile(final SortedSet files) {
	totalCurrentLOCPerFile = 0;
	totalNumRevision = 0;
	int fileNumber = 0;
	totalMisMatch = 0;
	numberMisMatch = 0;
	for (final Iterator it = files.iterator(); it.hasNext();) {
		final VersionedFile rev = (VersionedFile) it.next();
		totalCurrentLOCPerFile += rev.getCurrentLinesOfCode();
		totalNumRevision += rev.getRevisions().size();
		SvnConfigurationOptions.getTaskLogger().info("File " + ++fileNumber + "/ " + rev.getFilenameWithPath() + " \tLOC:" + rev.getCurrentLinesOfCode());
		int sumDelta = 0;
		// go through all revisions for this file.
		for (final Iterator it2 = rev.getRevisions().iterator(); it2.hasNext();) {
			final Revision revi = (Revision) it2.next();

			sumDelta += revi.getLinesDelta();
			if (revi.isBeginOfLog()) {
				sumDelta += revi.getLines();
			}
			SvnConfigurationOptions.getTaskLogger()
			        .info(
			                "\tRevision:" + padRight(revi.getRevisionNumber(), WIDTH_FOR_NUMBER) + " \tDelta:"
			                        + padIntRight(revi.getLinesDelta(), WIDTH_FOR_NUMBER) + "\tLines:" + padIntRight(revi.getLines(), WIDTH_FOR_NUMBER)
			                        + "\t" + printBoolean("Ini:", revi.isInitialRevision()) + "\t" + printBoolean("BegLog", revi.isBeginOfLog()) + "\t"
			                        + printBoolean("Dead", revi.isDead()) + "\tSumDelta:" + padIntRight(sumDelta, WIDTH_FOR_NUMBER) + " "
			                        + revi.getSymbolicNames());
		}
		if (sumDelta != rev.getCurrentLinesOfCode()) {
			SvnConfigurationOptions.getTaskLogger().info(
			        "\t~~~~~SUM DELTA DOES NOT MATCH LOC " + rev.getCurrentLinesOfCode() + " vs " + sumDelta + " Diff:"
			                + (rev.getCurrentLinesOfCode() - sumDelta) + " ~~~~~~");
			totalMisMatch += (rev.getCurrentLinesOfCode() - sumDelta);
			numberMisMatch++;
		}
	}
}
 
Example 12
Source Project: j2objc   File: TreeSubSetTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * subSet returns set with keys in requested range
 */
public void testSubSetContents() {
    NavigableSet set = set5();
    SortedSet sm = set.subSet(two, four);
    assertEquals(two, sm.first());
    assertEquals(three, sm.last());
    assertEquals(2, sm.size());
    assertFalse(sm.contains(one));
    assertTrue(sm.contains(two));
    assertTrue(sm.contains(three));
    assertFalse(sm.contains(four));
    assertFalse(sm.contains(five));
    Iterator i = sm.iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    k = (Integer)(i.next());
    assertEquals(three, k);
    assertFalse(i.hasNext());
    Iterator j = sm.iterator();
    j.next();
    j.remove();
    assertFalse(set.contains(two));
    assertEquals(4, set.size());
    assertEquals(1, sm.size());
    assertEquals(three, sm.first());
    assertEquals(three, sm.last());
    assertTrue(sm.remove(three));
    assertTrue(sm.isEmpty());
    assertEquals(3, set.size());
}
 
Example 13
Source Project: Tomcat8-Source-Read   File: HostConfig.java    License: MIT License 4 votes vote down vote up
/**
 * Check for old versions of applications using parallel deployment that are
 * now unused (have no active sessions) and undeploy any that are found.
 */
public synchronized void checkUndeploy() {
    if (deployed.size() < 2) {
        return;
    }

    // Need ordered set of names
    SortedSet<String> sortedAppNames = new TreeSet<>();
    sortedAppNames.addAll(deployed.keySet());

    Iterator<String> iter = sortedAppNames.iterator();

    ContextName previous = new ContextName(iter.next(), false);
    do {
        ContextName current = new ContextName(iter.next(), false);

        if (current.getPath().equals(previous.getPath())) {
            // Current and previous are same path - current will always
            // be a later version
            Context previousContext = (Context) host.findChild(previous.getName());
            Context currentContext = (Context) host.findChild(current.getName());
            if (previousContext != null && currentContext != null &&
                    currentContext.getState().isAvailable() &&
                    !isServiced(previous.getName())) {
                Manager manager = previousContext.getManager();
                if (manager != null) {
                    int sessionCount;
                    if (manager instanceof DistributedManager) {
                        sessionCount = ((DistributedManager) manager).getActiveSessionsFull();
                    } else {
                        sessionCount = manager.getActiveSessions();
                    }
                    if (sessionCount == 0) {
                        if (log.isInfoEnabled()) {
                            log.info(sm.getString(
                                    "hostConfig.undeployVersion", previous.getName()));
                        }
                        DeployedApplication app = deployed.get(previous.getName());
                        String[] resources = app.redeployResources.keySet().toArray(new String[0]);
                        // Version is unused - undeploy it completely
                        // The -1 is a 'trick' to ensure all redeploy
                        // resources are removed
                        undeploy(app);
                        deleteRedeployResources(app, resources, -1, true);
                    }
                }
            }
        }
        previous = current;
    } while (iter.hasNext());
}
 
Example 14
private static Hop constructReplacement(final Set<BinaryOp> emults, final Map<Hop, Integer> leaves) {
	// Sort by data type
	final SortedSet<Hop> sorted = new TreeSet<>(compareByDataType);
	for (final Map.Entry<Hop, Integer> entry : leaves.entrySet()) {
		final Hop h = entry.getKey();
		// unlink parents that are in the emult set(we are throwing them away)
		// keep other parents
		h.getParent().removeIf(parent -> parent instanceof BinaryOp && emults.contains(parent));
		sorted.add(constructPower(h, entry.getValue()));
	}
	// sorted contains all leaves, sorted by data type, stripped from their parents

	// Construct right-deep EMult tree
	final Iterator<Hop> iterator = sorted.iterator();

	Hop next = iterator.hasNext() ? iterator.next() : null;
	Hop colVectorsScalars = null;
	while(next != null &&
			(next.getDataType() == DataType.SCALAR
					|| next.getDataType() == DataType.MATRIX && next.getDim2() == 1))
	{
		if( colVectorsScalars == null )
			colVectorsScalars = next;
		else {
			colVectorsScalars = HopRewriteUtils.createBinary(next, colVectorsScalars, Hop.OpOp2.MULT);
			colVectorsScalars.setVisited();
		}
		next = iterator.hasNext() ? iterator.next() : null;
	}
	// next is not processed and is either null or past col vectors

	Hop rowVectors = null;
	while(next != null &&
			(next.getDataType() == DataType.MATRIX && next.getDim1() == 1))
	{
		if( rowVectors == null )
			rowVectors = next;
		else {
			rowVectors = HopRewriteUtils.createBinary(rowVectors, next, Hop.OpOp2.MULT);
			rowVectors.setVisited();
		}
		next = iterator.hasNext() ? iterator.next() : null;
	}
	// next is not processed and is either null or past row vectors

	Hop matrices = null;
	while(next != null &&
			(next.getDataType() == DataType.MATRIX))
	{
		if( matrices == null )
			matrices = next;
		else {
			matrices = HopRewriteUtils.createBinary(matrices, next, Hop.OpOp2.MULT);
			matrices.setVisited();
		}
		next = iterator.hasNext() ? iterator.next() : null;
	}
	// next is not processed and is either null or past matrices

	Hop other = null;
	while(next != null)
	{
		if( other == null )
			other = next;
		else {
			other = HopRewriteUtils.createBinary(other, next, Hop.OpOp2.MULT);
			other.setVisited();
		}
		next = iterator.hasNext() ? iterator.next() : null;
	}
	// finished

	// ((other * matrices) * rowVectors) * colVectorsScalars
	Hop top = null;
	if( other == null && matrices != null )
		top = matrices;
	else if( other != null && matrices == null )
		top = other;
	else if( other != null ) { //matrices != null
		top = HopRewriteUtils.createBinary(other, matrices, Hop.OpOp2.MULT);
		top.setVisited();
	}

	if( top == null && rowVectors != null )
		top = rowVectors;
	else if( rowVectors != null ) { //top != null
		top = HopRewriteUtils.createBinary(top, rowVectors, Hop.OpOp2.MULT);
		top.setVisited();
	}

	if( top == null && colVectorsScalars != null )
		top = colVectorsScalars;
	else if( colVectorsScalars != null ) { //top != null
		top = HopRewriteUtils.createBinary(top, colVectorsScalars, Hop.OpOp2.MULT);
		top.setVisited();
	}

	return top;
}
 
Example 15
Source Project: netbeans   File: PathMatcher.java    License: Apache License 2.0 4 votes vote down vote up
private Set<String> computeKnownIncludes() {
    if (includes == null) {
        return Collections.emptySet();
    }
    SortedSet<String> roots = new TreeSet<String>();
    StringTokenizer patternstok = new StringTokenizer(includes, ", "); // NOI18N
    boolean search = false;
    while (patternstok.hasMoreTokens()) {
        String pattern = patternstok.nextToken().replace('\\', '/').replaceFirst("/\\*\\*$", "/"); // NOI18N
        if (pattern.equals("**")) { // NOI18N
            roots.add(""); // NOI18N
        } else if (pattern.indexOf('*') == -1 && pattern.endsWith("/")) { // NOI18N
            // Optimize in case all includes are wildcard-free paths from root.
            if (excludePattern == null || !excludePattern.matcher(pattern).matches()) {
                String parent = pattern.substring(0, pattern.lastIndexOf('/', pattern.length() - 2) + 1);
                if (!includePattern.matcher(parent).matches()) {
                    roots.add(pattern);
                }
            }
        } else if (base != null) {
            // Optimization failed. Need to search for actual matches.
            search = true;
        }
    }
    // Verify that roots really exist, even if they are wilcard-free.
    if (base != null && base.isDirectory()) {
        Iterator<String> it = roots.iterator();
        while (it.hasNext()) {
            if (!new File(base, it.next().replace('/', File.separatorChar)).isDirectory()) {
                it.remove();
            }
        }
    }
    if (search) {
        // Find what dirs inside root actually match the path, so we known which parents to include later.
        // XXX note that this fails to listen to file creations & deletions inside the root so the result
        // can become inaccurate. Not clear how to efficiently solve that.
        findMatches(base, "", roots);
    }
    return roots;
}
 
Example 16
Source Project: lucene-solr   File: LevenshteinAutomata.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Expert: specify a custom maximum possible symbol
 * (alphaMax); default is Character.MAX_CODE_POINT.
 */
public LevenshteinAutomata(int[] word, int alphaMax, boolean withTranspositions) {
  this.word = word;
  this.alphaMax = alphaMax;

  // calculate the alphabet
  SortedSet<Integer> set = new TreeSet<>();
  for (int i = 0; i < word.length; i++) {
    int v = word[i];
    if (v > alphaMax) {
      throw new IllegalArgumentException("alphaMax exceeded by symbol " + v + " in word");
    }
    set.add(v);
  }
  alphabet = new int[set.size()];
  Iterator<Integer> iterator = set.iterator();
  for (int i = 0; i < alphabet.length; i++)
    alphabet[i] = iterator.next();
    
  rangeLower = new int[alphabet.length + 2];
  rangeUpper = new int[alphabet.length + 2];
  // calculate the unicode range intervals that exclude the alphabet
  // these are the ranges for all unicode characters not in the alphabet
  int lower = 0;
  for (int i = 0; i < alphabet.length; i++) {
    int higher = alphabet[i];
    if (higher > lower) {
      rangeLower[numRanges] = lower;
      rangeUpper[numRanges] = higher - 1;
      numRanges++;
    }
    lower = higher + 1;
  }
  /* add the final endpoint */
  if (lower <= alphaMax) {
    rangeLower[numRanges] = lower;
    rangeUpper[numRanges] = alphaMax;
    numRanges++;
  }

  descriptions = new ParametricDescription[] {
      null, /* for n=0, we do not need to go through the trouble */
      withTranspositions ? new Lev1TParametricDescription(word.length) : new Lev1ParametricDescription(word.length),
      withTranspositions ? new Lev2TParametricDescription(word.length) : new Lev2ParametricDescription(word.length),
  };
}
 
Example 17
private static SortedSet<ArtifactVersion> resolveAssociatedVersions( VersionsHelper helper,
                                                                     Set<ArtifactAssociation> associations,
                                                                     VersionComparator versionComparator )
    throws ArtifactMetadataRetrievalException
{
    SortedSet<ArtifactVersion> versions = null;
    for ( ArtifactAssociation association : associations )
    {
        final ArtifactVersions associatedVersions =
            helper.lookupArtifactVersions( association.getArtifact(), association.isUsePluginRepositories() );
        if ( versions != null )
        {
            final ArtifactVersion[] artifactVersions = associatedVersions.getVersions( true );
            // since ArtifactVersion does not override equals, we have to do this the hard way
            // result.retainAll( Arrays.asList( artifactVersions ) );
            Iterator j = versions.iterator();
            while ( j.hasNext() )
            {
                boolean contains = false;
                ArtifactVersion version = (ArtifactVersion) j.next();
                for ( ArtifactVersion artifactVersion : artifactVersions )
                {
                    if ( version.compareTo( artifactVersion ) == 0 )
                    {
                        contains = true;
                        break;
                    }
                }
                if ( !contains )
                {
                    j.remove();
                }
            }
        }
        else
        {
            versions = new TreeSet<>( versionComparator );
            versions.addAll( Arrays.asList( associatedVersions.getVersions( true ) ) );
        }
    }
    if ( versions == null )
    {
        versions = new TreeSet<>( versionComparator );
    }
    return Collections.unmodifiableSortedSet( versions );
}
 
Example 18
/**
 * Returns the Attr[]s to be output for the given element.
 * <br>
 * The code of this method is a copy of {@link #handleAttributes(Element,
 * NameSpaceSymbTable)},
 * whereas it takes into account that subtree-c14n is -- well --
 * subtree-based.
 * So if the element in question isRoot of c14n, it's parent is not in the
 * node set, as well as all other ancestors.
 *
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
    throws CanonicalizationException {
    if (!element.hasAttributes() && !firstCall) {
        return null;
    }
    // result will contain the attrs which have to be output
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                // It's not a namespace attr node. Add to the result and continue.
                result.add(attribute);
            } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
                // The default mapping for xml must not be output.
                Node n = ns.addMappingAndRender(NName, NValue, attribute);

                if (n != null) {
                    // Render the ns definition
                    result.add((Attr)n);
                    if (C14nHelper.namespaceIsRelative(attribute)) {
                        Object exArgs[] = {element.getTagName(), NName, attribute.getNodeValue()};
                        throw new CanonicalizationException(
                            "c14n.Canonicalizer.RelativeNamespace", exArgs
                        );
                    }
                }
            }
        }
    }

    if (firstCall) {
        // It is the first node of the subtree
        // Obtain all the namespaces defined in the parents, and added to the output.
        ns.getUnrenderedNodes(result);
        // output the attributes in the xml namespace.
        xmlattrStack.getXmlnsAttr(result);
        firstCall = false;
    }

    return result.iterator();
}
 
Example 19
/**
 * Returns the Attr[]s to be output for the given element.
 * <br>
 * The code of this method is a copy of {@link #handleAttributes(Element,
 * NameSpaceSymbTable)},
 * whereas it takes into account that subtree-c14n is -- well -- subtree-based.
 * So if the element in question isRoot of c14n, it's parent is not in the
 * node set, as well as all other ancestors.
 *
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributesSubtree(Element element, NameSpaceSymbTable ns)
    throws CanonicalizationException {
    if (!element.hasAttributes() && !firstCall) {
        return null;
    }
    // result will contain the attrs which have to be output
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                //It's not a namespace attr node. Add to the result and continue.
                result.add(attribute);
            } else if (!(XML.equals(NName) && XML_LANG_URI.equals(NValue))) {
                //The default mapping for xml must not be output.
                Node n = ns.addMappingAndRender(NName, NValue, attribute);

                if (n != null) {
                    //Render the ns definition
                    result.add((Attr)n);
                    if (C14nHelper.namespaceIsRelative(attribute)) {
                        Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
                        throw new CanonicalizationException(
                            "c14n.Canonicalizer.RelativeNamespace", exArgs
                        );
                    }
                }
            }
        }
    }

    if (firstCall) {
        //It is the first node of the subtree
        //Obtain all the namespaces defined in the parents, and added to the output.
        ns.getUnrenderedNodes(result);
        //output the attributes in the xml namespace.
        xmlattrStack.getXmlnsAttr(result);
        firstCall = false;
    }

    return result.iterator();
}
 
Example 20
Source Project: hottub   File: EnvHelp.java    License: GNU General Public License v2.0 4 votes vote down vote up
private static void hideAttributes(SortedMap<String, ?> map) {
    if (map.isEmpty())
        return;

    final SortedSet<String> hiddenStrings;
    final SortedSet<String> hiddenPrefixes;

    String hide = (String) map.get(HIDDEN_ATTRIBUTES);
    if (hide != null) {
        if (hide.startsWith("="))
            hide = hide.substring(1);
        else
            hide += " " + DEFAULT_HIDDEN_ATTRIBUTES;
        hiddenStrings = new TreeSet<String>();
        hiddenPrefixes = new TreeSet<String>();
        parseHiddenAttributes(hide, hiddenStrings, hiddenPrefixes);
    } else {
        hide = DEFAULT_HIDDEN_ATTRIBUTES;
        synchronized (defaultHiddenStrings) {
            if (defaultHiddenStrings.isEmpty()) {
                parseHiddenAttributes(hide,
                                      defaultHiddenStrings,
                                      defaultHiddenPrefixes);
            }
            hiddenStrings = defaultHiddenStrings;
            hiddenPrefixes = defaultHiddenPrefixes;
        }
    }

    /* Construct a string that is greater than any key in the map.
       Setting a string-to-match or a prefix-to-match to this string
       guarantees that we will never call next() on the corresponding
       iterator.  */
    String sentinelKey = map.lastKey() + "X";
    Iterator<String> keyIterator = map.keySet().iterator();
    Iterator<String> stringIterator = hiddenStrings.iterator();
    Iterator<String> prefixIterator = hiddenPrefixes.iterator();

    String nextString;
    if (stringIterator.hasNext())
        nextString = stringIterator.next();
    else
        nextString = sentinelKey;
    String nextPrefix;
    if (prefixIterator.hasNext())
        nextPrefix = prefixIterator.next();
    else
        nextPrefix = sentinelKey;

    /* Read each key in sorted order and, if it matches a string
       or prefix, remove it. */
keys:
    while (keyIterator.hasNext()) {
        String key = keyIterator.next();

        /* Continue through string-match values until we find one
           that is either greater than the current key, or equal
           to it.  In the latter case, remove the key.  */
        int cmp = +1;
        while ((cmp = nextString.compareTo(key)) < 0) {
            if (stringIterator.hasNext())
                nextString = stringIterator.next();
            else
                nextString = sentinelKey;
        }
        if (cmp == 0) {
            keyIterator.remove();
            continue keys;
        }

        /* Continue through the prefix values until we find one
           that is either greater than the current key, or a
           prefix of it.  In the latter case, remove the key.  */
        while (nextPrefix.compareTo(key) <= 0) {
            if (key.startsWith(nextPrefix)) {
                keyIterator.remove();
                continue keys;
            }
            if (prefixIterator.hasNext())
                nextPrefix = prefixIterator.next();
            else
                nextPrefix = sentinelKey;
        }
    }
}