Java Code Examples for java.util.List#listIterator()

The following examples show how to use java.util.List#listIterator() . 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
Source File: CategoryWorker.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * SCIPIO: Checks the given trail for the last recorded top category ID, if any.
 * This can be the catalog top category or a different one.
 * <p>
 * NOTE: is caching
 */
public static String getTopCategoryFromTrail(Delegator delegator, LocalDispatcher dispatcher, List<String> trail) {
    String catId = null;
    if (trail != null) {
        ListIterator<String> it = trail.listIterator(trail.size());
        while (it.hasPrevious()) {
            catId = it.previous();
            if (UtilValidate.isNotEmpty(catId) && !"TOP".equals(catId)) {
                if (isCategoryTop(delegator, dispatcher, catId)) {
                    return catId;
                }
            }
        }
    }
    return null;
}
 
Example 2
Source File: RunTimeDDCatalog.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Get String iterator representing all public IDs registered in catalog.
 * @return null if cannot proceed, try later.
 */
@Override
public Iterator getPublicIDs() {
    if (platformRootDir == null) {
        return null;
    }
    if (!platformRootDir.exists()) {
        return null;
    }
    
    String installRoot = platformRootDir.getAbsolutePath(); 
    if (installRoot == null) {
        return null;
    }
    
    List<String> list = new ArrayList<String>();
    for (int i=0;i<TypeToURLMap.length;i = i+2){
        list.add(TypeToURLMap[i]);
    }
    if (hasAdditionalMap) {
        for (int i=0;i<JavaEE6TypeToURLMap.length;i = i+2){
            list.add(JavaEE6TypeToURLMap[i]);
        }
    }
    for (int i=0;i<SchemaToURLMap.length;i = i+2){
        list.add(SchemaToURLMap[i]);
    }
    if (hasAdditionalMap) {
        for (int i=0;i<JavaEE6SchemaToURLMap.length;i = i+2){
            list.add(JavaEE6SchemaToURLMap[i]);
        }
    }
    
    return list.listIterator();
}
 
Example 3
Source File: PatchForUpdatingTagsJson_J10020.java    From ranger with Apache License 2.0 5 votes vote down vote up
TagRetrieverTagDefContext(XXService xService) {
    Long                    serviceId         = xService == null ? null : xService.getId();
    List<XXTagDef>          xTagDefs          = daoMgr.getXXTagDef().findByServiceId(serviceId);
    List<XXTagAttributeDef> xTagAttributeDefs = daoMgr.getXXTagAttributeDef().findByServiceId(serviceId);

    this.service             = xService;
    this.iterTagDef          = xTagDefs.listIterator();
    this.iterTagAttributeDef = xTagAttributeDefs.listIterator();
}
 
Example 4
Source File: DocCommentLookup.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Select comment closest to lookup element. Assume comments to be ordered list. Ignores comments starting with
 * doublestar.
 *
 * @param comments
 *            list of commnets on luukup elements
 * @throws InstantiationException
 *             if comment is malformed
 */
protected CommentCandidate pickCommentNoDoubleStar(List<INode> comments) throws InstantiationException {
	ListIterator<INode> iter = comments.listIterator(comments.size());
	String candidateTextString = null;
	while (iter.hasPrevious()) {
		candidateTextString = iter.previous().getText();
		if (!candidateTextString.startsWith("/**")) {
			return new CommentCandidate(candidateTextString);
		}
	}
	return null;
}
 
Example 5
Source File: BaseAnalyzerPresenter.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
@Override
public final void processUrlList(List<String> result) {
    if (result == null) return;
    ListIterator<String> iterator = result.listIterator();
    while (iterator.hasNext()) {
        iterator.set(URLUtils.getAbsUrl(getBaseURL(), iterator.next()));
    }
}
 
Example 6
Source File: CheckListTag.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Starting from the module <code>buttonsSB</code> object, 
 * creates all buttons for the jsp list. 
 * @param buttons The list of the buttons 
 * 
 * @throws JspException If any exception occurs.
 */

protected StringBuffer makeButton(List buttons) throws JspException {

	StringBuffer htmlStream = new StringBuffer();

	Iterator iter = buttons.listIterator();
	while (iter.hasNext()) {
		SourceBeanAttribute buttonSBA = (SourceBeanAttribute)iter.next();
		SourceBean buttonSB = (SourceBean)buttonSBA.getValue();
		List parameters = buttonSB.getAttributeAsList("PARAMETER");
		HashMap paramsMap = getParametersMap(parameters, null);
		
		String name = (String) buttonSB.getAttribute("name");
		String img = (String) buttonSB.getAttribute("image");
		String labelCode = (String) buttonSB.getAttribute("label");			
		String label = msgBuilder.getMessage(labelCode, _bundle, httpRequest);
		
		PortletURL buttonUrl = createUrl(paramsMap);
		
		htmlStream.append("<td class=\"header-button-column-portlet-section\">\n");
		htmlStream.append("<input type='image' " +
								  "name='" + name + "' " +
								  "title='" + label + "' " +
								  "class='header-button-image-portlet-section'" + 	
								  "src ='"+ renderResponse.encodeURL(renderRequest.getContextPath() + img) + "' " +
								  "alt='" + label + "'>\n");
		htmlStream.append("</td>\n");
	}
	
	return htmlStream;
}
 
Example 7
Source File: StrUtils.java    From jclic with GNU General Public License v2.0 5 votes vote down vote up
public static String getEnumeration(List<String> items) {
  StringBuilder sb = new StringBuilder();
  ListIterator<String> it = items.listIterator();

  while (it.hasNext())
    StrUtils.addToEnum(sb, it.next(), ", ");

  return sb.toString();
}
 
Example 8
Source File: PatchForUpdatingPolicyJson_J10019.java    From ranger with Apache License 2.0 5 votes vote down vote up
RetrieverContext(XXService xService) {
	Long           serviceId = xService == null ? null : xService.getId();
	List<XXPolicy> xPolicies = daoMgr.getXXPolicy().findByServiceId(serviceId);

	this.service    = xService;
	this.iterPolicy = xPolicies.listIterator();

	List<XXPolicyResource>          xResources      = daoMgr.getXXPolicyResource().findByServiceId(serviceId);
	List<XXPolicyResourceMap>       xResourceMaps   = daoMgr.getXXPolicyResourceMap().findByServiceId(serviceId);
	List<XXPolicyItem>              xPolicyItems    = daoMgr.getXXPolicyItem().findByServiceId(serviceId);
	List<XXPolicyItemUserPerm>      xUserPerms      = daoMgr.getXXPolicyItemUserPerm().findByServiceId(serviceId);
	List<XXPolicyItemGroupPerm>     xGroupPerms     = daoMgr.getXXPolicyItemGroupPerm().findByServiceId(serviceId);
	List<XXPolicyItemAccess>        xAccesses       = daoMgr.getXXPolicyItemAccess().findByServiceId(serviceId);
	List<XXPolicyItemCondition>     xConditions     = daoMgr.getXXPolicyItemCondition().findByServiceId(serviceId);
	List<XXPolicyItemDataMaskInfo>  xDataMaskInfos  = daoMgr.getXXPolicyItemDataMaskInfo().findByServiceId(serviceId);
	List<XXPolicyItemRowFilterInfo> xRowFilterInfos = daoMgr.getXXPolicyItemRowFilterInfo().findByServiceId(serviceId);
             List<XXPolicyLabelMap>          xPolicyLabelMap = daoMgr.getXXPolicyLabelMap().findByServiceId(serviceId);

	this.iterResources      = xResources.listIterator();
	this.iterResourceMaps   = xResourceMaps.listIterator();
	this.iterPolicyItems    = xPolicyItems.listIterator();
	this.iterUserPerms      = xUserPerms.listIterator();
	this.iterGroupPerms     = xGroupPerms.listIterator();
	this.iterAccesses       = xAccesses.listIterator();
	this.iterConditions     = xConditions.listIterator();
	this.iterDataMaskInfos  = xDataMaskInfos.listIterator();
	this.iterRowFilterInfos = xRowFilterInfos.listIterator();
             this.iterPolicyLabels   = xPolicyLabelMap.listIterator();
}
 
Example 9
Source File: CodeShrinkVisitor.java    From jadx with Apache License 2.0 5 votes vote down vote up
private static void shrinkBlock(MethodNode mth, BlockNode block) {
	if (block.getInstructions().isEmpty()) {
		return;
	}
	InsnList insnList = new InsnList(block.getInstructions());
	int insnCount = insnList.size();
	List<ArgsInfo> argsList = new ArrayList<>(insnCount);
	for (int i = 0; i < insnCount; i++) {
		argsList.add(new ArgsInfo(insnList.get(i), argsList, i));
	}
	List<WrapInfo> wrapList = new ArrayList<>();
	for (ArgsInfo argsInfo : argsList) {
		List<RegisterArg> args = argsInfo.getArgs();
		if (!args.isEmpty()) {
			ListIterator<RegisterArg> it = args.listIterator(args.size());
			while (it.hasPrevious()) {
				RegisterArg arg = it.previous();
				checkInline(mth, block, insnList, wrapList, argsInfo, arg);
			}
		}
	}
	if (!wrapList.isEmpty()) {
		for (WrapInfo wrapInfo : wrapList) {
			inline(mth, wrapInfo.getArg(), wrapInfo.getInsn(), block);
		}
	}
}
 
Example 10
Source File: IteratorDefaults.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void testOptimizedForEach() throws Exception {
    final Integer[] data = new Integer[1000 * 1000];
    for (int i=0; i < data.length; i++) {
        data[i] = i;
    }
    final List<Integer> source = Arrays.asList(data);

    final String[] listClasses = {
            "java.util.ArrayList",
            "java.util.LinkedList",
            "java.util.Vector",
            "java.util.concurrent.CopyOnWriteArrayList"
    };

    final int OFFSET = 3;
    final List<Integer> target = new ArrayList<>(source);
    for (final String listClass : listClasses) {
        final List<Integer> list =
                (List<Integer>) Class.forName(listClass).newInstance();
        list.addAll(source);
        final ListIterator<Integer> iterator = list.listIterator();
        assertFalse(iterator.hasPrevious());
        for (int i=0; i < OFFSET; i++) {
            iterator.next();
        }
        assertTrue(iterator.hasNext());
        assertTrue(iterator.hasPrevious());
        assertEquals(iterator.nextIndex(), OFFSET);
        assertEquals(iterator.previousIndex(), OFFSET - 1);

        iterator.forEachRemaining(e -> {
            target.set(e, e + 1);
        });
        for (int i=OFFSET; i < data.length; i++) {
            assertEquals(target.get(i).intValue(), source.get(i)+1);
        }

        assertFalse(iterator.hasNext());
        assertTrue(iterator.hasPrevious());
        assertEquals(iterator.nextIndex(), data.length);
        assertEquals(iterator.previousIndex(), data.length - 1);

        // CopyOnWriteArrayList.listIterator().remove() is unsupported
        if (!"java.util.concurrent.CopyOnWriteArrayList".equals(listClass)) {
            for (int i = data.length - 1; i >= 0; i--) {
                iterator.remove(); // must not throw
                if (i > 0) {
                    iterator.previous();
                }
            }
            assertTrue(list.isEmpty());
        }

        try {
            iterator.next();
            fail(listClass + " iterator advanced beyond end");
        } catch (NoSuchElementException ignore) {
        }
    }
}
 
Example 11
Source File: HeaderImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
protected Iterator<SOAPHeaderElement> getHeaderElements(
    String actor,
    boolean detach,
    boolean mustUnderstand) {
    List<SOAPHeaderElement> elementList = new ArrayList<>();

    Iterator<javax.xml.soap.Node> eachChild = getChildElements();

    org.w3c.dom.Node currentChild = iterate(eachChild);
    while (currentChild != null) {
        if (!(currentChild instanceof SOAPHeaderElement)) {
            currentChild = iterate(eachChild);
        } else {
            HeaderElementImpl currentElement =
                (HeaderElementImpl) currentChild;
            currentChild = iterate(eachChild);

            boolean isMustUnderstandMatching =
                (!mustUnderstand || currentElement.getMustUnderstand());
            boolean doAdd = false;
            if (actor == null && isMustUnderstandMatching) {
                doAdd = true;
            } else {
                String currentActor = currentElement.getActorOrRole();
                if (currentActor == null) {
                    currentActor = "";
                }

                if (currentActor.equalsIgnoreCase(actor)
                    && isMustUnderstandMatching) {
                    doAdd = true;
                }
            }

            if (doAdd) {
                elementList.add(currentElement);
                if (detach) {
                    currentElement.detachNode();
                }
            }
        }
    }

    return elementList.listIterator();
}
 
Example 12
Source File: ClassObject.java    From JDeodorant with MIT License 4 votes vote down vote up
public ListIterator<TypeObject> getSuperclassIterator() {
	List<TypeObject> superclassList = new ArrayList<TypeObject>(interfaceList);
	superclassList.add(superclass);
	return superclassList.listIterator();
}
 
Example 13
Source File: RegisterAssigner.java    From JAADAS with GNU General Public License v3.0 4 votes vote down vote up
public InstructionIterator(List<Insn> insns, Map<Insn, Stmt> insnStmtMap, Map<Insn, LocalRegisterAssignmentInformation> insnRegisterMap) {
	this.insnStmtMap = insnStmtMap;
	this.insnsIterator = insns.listIterator(); 
	this.insnRegisterMap = insnRegisterMap;
}
 
Example 14
Source File: LocalNoteList.java    From org.openntf.domino with Apache License 2.0 4 votes vote down vote up
public LocalNoteListIterator(final List<LocalNoteCoordinate> delegate, final LocalNoteList parent, final int index) {
	parent_ = parent;
	delegate_ = delegate.listIterator(index);
}
 
Example 15
Source File: Lower.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructor.
 */
Lower(final Compiler compiler) {
    super(new BlockLexicalContext() {

        @Override
        public List<Statement> popStatements() {
            final List<Statement> newStatements = new ArrayList<>();
            boolean terminated = false;

            final List<Statement> statements = super.popStatements();
            for (final Statement statement : statements) {
                if (!terminated) {
                    newStatements.add(statement);
                    if (statement.isTerminal() || statement instanceof JumpStatement) { //TODO hasGoto? But some Loops are hasGoto too - why?
                        terminated = true;
                    }
                } else {
                    FoldConstants.extractVarNodesFromDeadCode(statement, newStatements);
                }
            }
            return newStatements;
        }

        @Override
        protected Block afterSetStatements(final Block block) {
            final List<Statement> stmts = block.getStatements();
            for(final ListIterator<Statement> li = stmts.listIterator(stmts.size()); li.hasPrevious();) {
                final Statement stmt = li.previous();
                // popStatements() guarantees that the only thing after a terminal statement are uninitialized
                // VarNodes. We skip past those, and set the terminal state of the block to the value of the
                // terminal state of the first statement that is not an uninitialized VarNode.
                if(!(stmt instanceof VarNode && ((VarNode)stmt).getInit() == null)) {
                    return block.setIsTerminal(this, stmt.isTerminal());
                }
            }
            return block.setIsTerminal(this, false);
        }
    });

    this.log = initLogger(compiler.getContext());
}
 
Example 16
Source File: Project.java    From pom-manipulation-ext with Apache License 2.0 4 votes vote down vote up
private void resolvePlugins( MavenSessionHandler session, List<Plugin> plugins, PluginResolver includeManagedPlugins,
                             Map<ProjectVersionRef, Plugin> resolvedPlugins )
                throws ManipulationException
{
    ListIterator<Plugin> iterator = plugins.listIterator( plugins.size() );

    // Iterate in reverse order so later plugins take precedence
    while ( iterator.hasPrevious() )
    {
        Plugin p = iterator.previous();

        String g = PropertyResolver.resolveInheritedProperties( session, this, "${project.groupId}".equals( p.getGroupId() ) ?
                        getGroupId() :
                        p.getGroupId() );
        String a = PropertyResolver.resolveInheritedProperties( session, this, "${project.artifactId}".equals( p.getArtifactId() ) ?
                        getArtifactId() :
                        p.getArtifactId() );
        String v = PropertyResolver.resolveInheritedProperties( session, this, p.getVersion() );

        // Its possible the internal plugin list is either abbreviated or empty. Attempt to fill in default values for
        // comparison purposes.
        if ( isEmpty( g ) )
        {
            g = PLUGIN_DEFAULTS.getDefaultGroupId( a );
        }
        if ( isEmpty( v ) )
        {
            // For managed plugins, if the version is blank we always check the default list.
            // If getAll* has been called then if we can't find a version in the default list, dummy one up.
            if ( includeManagedPlugins == PluginResolver.ALL || includeManagedPlugins == PluginResolver.PLUGIN_DEFAULTS)
            {
                v = PLUGIN_DEFAULTS.getDefaultVersion( g, a );
                if ( "[0.0.0.1,]".equals( v ) )
                {
                    v = "";
                }
            }
            if ( isEmpty( v ) && includeManagedPlugins == PluginResolver.ALL )
            {
                v = "*";
            }
        }
        // Theoretically we could default an empty v via PLUGIN_DEFAULTS.getDefaultVersion( g, a ) but
        // this means managed plugins would be included which confuses things.
        if ( isNotEmpty( g ) && isNotEmpty( a ) && isNotEmpty( v ) )
        {
            SimpleProjectVersionRef spv = new SimpleProjectVersionRef( g, a, v );

            // If the GAV already exists within the map it means we have a duplicate entry. While Maven
            // technically allows this it does warn that this leads to unstable models. In PME case this breaks
            // the indexing as we don't have duplicate entries. Given they are exact matches, remove older duplicate.
            if ( resolvedPlugins.containsKey( spv ) )
            {
                logger.error( "Found duplicate entry within plugin list. Key of {} and plugin {}", spv, p );
                iterator.remove();
            }
            else
            {
                Plugin old = resolvedPlugins.put( spv, p );

                if ( old != null )
                {
                    logger.error( "Internal project plugin resolution failure ; replaced {} in store by {}.", old,
                                  spv );
                    throw new ManipulationException( "Internal project plugin resolution failure ; replaced {} in store by {}.", old,
                                                     spv);
                }
            }
        }
    }
}
 
Example 17
Source File: NeuroML.java    From TrakEM2 with GNU General Public License v3.0 4 votes vote down vote up
/** Without headers, just the cell block for a single Treeline.
 * If pre is null, then synapses are not collected. */
static private final void exportMorphMLCell(final Writer w, final Treeline t,
		final Set<Tree<?>> trees, final List<HalfSynapse> pre, final List<HalfSynapse> post,
		final AffineTransform scale2d, final double zScale) throws IOException
{	
	final float[] fp = new float[4]; // x, y, z, r

	// Prepare transform
	final AffineTransform aff = new AffineTransform(t.getAffineTransform());
	aff.preConcatenate(scale2d);

	writeCellHeader(w, t);

	// Map of Node vs id of the node
	// These ids are used to express parent-child relationships between segments
	final HashMap<Node<Float>,Long> nodeIds = new HashMap<Node<Float>,Long>();

	// Map of coords for branch or end nodes
	// so that the start of a cable can write the proximal coords
	final HashMap<Node<Float>,float[]> nodeCoords = new HashMap<Node<Float>,float[]>();

	// Root gets ID of 0:
	long nextSegmentId = 0;
	long cableId = 0;
	final Node<Float> root = t.getRoot();

	toPoint(root, fp, aff, zScale);
	writeSomaSegment(w, fp); // a dummy segment that has no length, and with a cableId of 0.
	if (null != pre) collectConnectors(root, t, fp, 0, pre, post);

	// Prepare
	nodeIds.put(root, nextSegmentId);
	nodeCoords.put(root, fp.clone());
	nextSegmentId += 1;
	cableId += 1;

	// All cables that come out of the Soma (the root) require a special tag:
	final HashSet<Long> somaCables = new HashSet<Long>();

	// Iterate all cables (all slabs; here a slab is synonym with cable, even if in NeuroML it doesn't have to be)
	for (final Node<Float> node : t.getRoot().getBranchAndEndNodes()) {
		// Gather the list of nodes all the way up to the previous branch node or root,
		// that last one not included.
		final List<Node<Float>> slab = cable(node);
		final String sCableId = Long.toString(cableId);
		// The id of the parent already exists, given that the Collection
		// is iterated depth-first from the root.
		final Node<Float> parent = slab.get(slab.size()-1).getParent();
		long parentId = nodeIds.get(parent);
		// Use the parent coords for the proximal coords of the first segment of the cable
		float[] parentCoords = nodeCoords.get(parent);
		// Is it a cable coming out of the root node (the soma) ?
		if (0 == parentId) somaCables.add(cableId);
		// For every node starting from the closest to the root (the last),
		// write a segment of the cable
		for (final ListIterator<Node<Float>> it = slab.listIterator(slab.size()); it.hasPrevious(); ) {
			// Assign an id to the node of the slab
			final Node<Float> seg = it.previous();
			// Write the segment
			toPoint(seg, fp, aff, zScale);
			writeCableSegment(w, fp, nextSegmentId, parentId, parentCoords, sCableId);
			// Inspect and collect synapses originating at this node
			if (null != pre) collectConnectors(seg, t, fp, nextSegmentId, pre, post);
			// Prepare next segment in the cable
			parentId = nextSegmentId;
			nextSegmentId += 1;
			parentCoords = null; // is used only for the first node
		}
		// Record the branch node, to be used for filling in "distal" fields
		if (node.getChildrenCount() > 1) {
			nodeIds.put(node, parentId); // parentId is the last used nextId, which is the id of node
			final float[] fpCopy = new float[4];
			toPoint(node, fpCopy, aff, zScale);
			nodeCoords.put(node, fpCopy);
		}

		// Prepare next slab or cable
		cableId += 1;
	}

	w.write(" </segments>\n");

	// Define the nature of each cable
	// Each cable requires a unique name
	w.write(" <cables xmlns=\"http://morphml.org/morphml/schema\">\n");
	w.write("  <cable id=\"0\" name=\"Soma\">\n   <meta:group>soma_group</meta:group>\n  </cable>\n");
	for (long i=1; i<cableId; i++) {
		final String sid = Long.toString(i);
		w.write("  <cable id=\""); w.write(sid);
		w.write("\" name=\""); w.write(sid);
		if (somaCables.contains(i)) w.write("\" fract_along_parent=\"0.5");
		else w.write("\" fract_along_parent=\"1.0"); // child segments start at the end of the segment
		w.write("\">\n   <meta:group>arbor_group</meta:group>\n  </cable>\n");
	}

	w.write(" </cables>\n</cell>\n");
}
 
Example 18
Source File: MesosResourceAllocation.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Takes some amount of range resources (e.g. ports).
 *
 * @param amount the number of values to take from the available range(s).
 * @param roles the roles to accept
 */
public List<Protos.Resource> takeRanges(String resourceName, int amount, Set<String> roles) {
	if (LOG.isDebugEnabled()) {
		LOG.debug("Allocating {} {}", amount, resourceName);
	}

	List<Protos.Resource> result = new ArrayList<>(1);
	for (ListIterator<Protos.Resource> i = resources.listIterator(); i.hasNext();) {
		if (amount <= 0) {
			break;
		}

		// take from next available range resource that is unreserved or reserved for an applicable role
		Protos.Resource available = i.next();
		if (!resourceName.equals(available.getName()) || !available.hasRanges()) {
			continue;
		}
		if (!UNRESERVED_ROLE.equals(available.getRole()) && !roles.contains(available.getRole())) {
			continue;
		}

		List<Protos.Value.Range> takenRanges = new ArrayList<>();
		List<Protos.Value.Range> remainingRanges = new ArrayList<>(available.getRanges().getRangeList());
		for (ListIterator<Protos.Value.Range> j = remainingRanges.listIterator(); j.hasNext();) {
			if (amount <= 0) {
				break;
			}

			// take from next available range (note: ranges are inclusive)
			Protos.Value.Range availableRange = j.next();
			long amountToTake = Math.min(availableRange.getEnd() - availableRange.getBegin() + 1, amount);
			Protos.Value.Range takenRange = availableRange.toBuilder().setEnd(availableRange.getBegin() + amountToTake - 1).build();
			amount -= amountToTake;
			takenRanges.add(takenRange);

			// keep remaining range (if any)
			long remaining = availableRange.getEnd() - takenRange.getEnd();
			if (remaining > 0) {
				j.set(availableRange.toBuilder().setBegin(takenRange.getEnd() + 1).build());
			}
			else {
				j.remove();
			}
		}
		Protos.Resource taken = available.toBuilder().setRanges(Protos.Value.Ranges.newBuilder().addAllRange(takenRanges)).build();
		if (LOG.isDebugEnabled()) {
			LOG.debug("Taking {} from {}", Utils.toString(taken.getRanges()), Utils.toString(available));
		}
		result.add(taken);

		// keep remaining ranges (if any)
		if (remainingRanges.size() > 0) {
			i.set(available.toBuilder().setRanges(Protos.Value.Ranges.newBuilder().addAllRange(remainingRanges)).build());
		}
		else {
			i.remove();
		}
	}

	if (LOG.isDebugEnabled()) {
		LOG.debug("Allocated: {}, unsatisfied: {}", Utils.toString(result), amount);
	}
	return result;
}
 
Example 19
Source File: BgpUpdateMsgTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * This test case checks update message with path attributes.
 */
@Test
public void bgpUpdateMessageTest07() throws BgpParseException {
    byte[] updateMsg = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
            (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
            (byte) 0xff, (byte) 0xff, 0x00, 0x3f, 0x02, 0x00, 0x00, 0x00, 0x1c, 0x40, 0x01, 0x01,
            0x00, 0x40, 0x02, 0x00, 0x40, 0x03, 0x04, 0x03, 0x03, 0x03, 0x03, (byte) 0x80, 0x04, 0x04, 0x00, 0x00,
            0x00, 0x00, 0x40, 0x05, 0x04, 0x00, 0x00, 0x00, 0x64, 0x18, 0x0a, 0x1e, 0x03, 0x18, 0x0a, 0x1e,
            0x02, 0x18, 0x0a, 0x1e, 0x01};

    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeBytes(updateMsg);

    BgpMessageReader<BgpMessage> reader = BgpFactories.getGenericReader();
    BgpMessage message;
    BgpHeader bgpHeader = new BgpHeader();

    message = reader.readFrom(buffer, bgpHeader);

    assertThat(message, instanceOf(BgpUpdateMsg.class));
    BgpUpdateMsg other = (BgpUpdateMsg) message;

    assertThat(other.getHeader().getMarker(), is(MARKER));
    assertThat(other.getHeader().getType(), is(UPDATE_MSG_TYPE));
    assertThat(other.getHeader().getLength(), is((short) 63));

    BgpValueType testPathAttribute;
    Origin origin;
    AsPath asPath;
    NextHop nexthop;
    Med med;
    LocalPref localPref;

    List<BgpValueType> pathAttributes = new LinkedList<>();
    BgpPathAttributes actualpathAttribute = other.bgpPathAttributes();
    pathAttributes = actualpathAttribute.pathAttributes();
    ListIterator<BgpValueType> listIterator = pathAttributes.listIterator();
    OriginType originValue = OriginType.IGP;

    testPathAttribute = listIterator.next();
    origin = (Origin) testPathAttribute;
    assertThat(origin.origin(), is(originValue));

    testPathAttribute = listIterator.next(); // AS PATH value is empty in hex dump
    asPath = (AsPath) testPathAttribute;
    List<Short> asPathValues = asPath.asPathSeq();
    assertThat(asPathValues.isEmpty(), is(true));

    testPathAttribute = listIterator.next();
    nexthop = (NextHop) testPathAttribute;
    byte[] nextHopAddr = new byte[] {0x03, 0x03, 0x03, 0x03};
    assertThat(nexthop.nextHop().toOctets(), is(nextHopAddr));

    testPathAttribute = listIterator.next();
    med = (Med) testPathAttribute;
    assertThat(med.med(), is(0));

    testPathAttribute = listIterator.next();
    localPref = (LocalPref) testPathAttribute;
    assertThat(localPref.localPref(), is(100));

    ListIterator<IpPrefix> listIterator1 = other.nlri().listIterator();
    byte[] prefix = new byte[] {0x0a, 0x1e, 0x03, 0x00};

    IpPrefix testPrefixValue = listIterator1.next();
    assertThat(testPrefixValue.prefixLength(), is((int) 24));
    assertThat(testPrefixValue.address().toOctets(), is(prefix));
}
 
Example 20
Source File: ListIteratorOf.java    From cactoos with MIT License 2 votes vote down vote up
/**
 * Ctor.
 * @param list List that will be called to get a list iterator.
 * @param index Start index for a newly created list iterator.
 */
public ListIteratorOf(final List<T> list, final int index) {
    this(() -> list.listIterator(index));
}