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

The following examples show how to use java.util.LinkedList#iterator() . 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: StringRange.java    From trekarta with GNU General Public License v3.0 6 votes vote down vote up
private static LinkedList<Ranges> compact(int size, Set<Ranges> inputRanges) {
    LinkedList<Ranges> ranges = new LinkedList<Ranges>(inputRanges);
    for (int i = size-1; i >= 0; --i) {
        Ranges last = null;
        for (Iterator<Ranges> it = ranges.iterator(); it.hasNext();) {
            Ranges item = it.next();
            if (last == null) {
                last = item;
            } else if (last.merge(i, item)) {
                it.remove();
            } else {
                last = item; // go to next
            }
        }
    };
    return ranges;
}
 
Example 2
Source File: SoldierRequests.java    From settlers-remake with MIT License 6 votes vote down vote up
SoldierRequest removeOne(ESoldierType soldierType) {
	LinkedList<SoldierRequest> classRequests = requestsByClass[soldierType.soldierClass.ordinal];

	if (classRequests.isEmpty()) {
		return null;
	}

	for (Iterator<SoldierRequest> iterator = classRequests.iterator(); iterator.hasNext();) { // check if there is a request with this soldier type
		SoldierRequest request = iterator.next();
		if (request.soldierType == soldierType) {
			iterator.remove();
			return request;
		}
	}

	return classRequests.removeFirst();
}
 
Example 3
Source File: NativeProtocol.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
public void dumpPacketRingBuffer() {
    // use local variable to allow unsynchronized usage of the buffer
    LinkedList<StringBuilder> localPacketDebugRingBuffer = this.packetDebugRingBuffer;
    if (localPacketDebugRingBuffer != null) {
        StringBuilder dumpBuffer = new StringBuilder();

        dumpBuffer.append("Last " + localPacketDebugRingBuffer.size() + " packets received from server, from oldest->newest:\n");
        dumpBuffer.append("\n");

        for (Iterator<StringBuilder> ringBufIter = localPacketDebugRingBuffer.iterator(); ringBufIter.hasNext();) {
            dumpBuffer.append(ringBufIter.next());
            dumpBuffer.append("\n");
        }

        this.log.logTrace(dumpBuffer.toString());
    }
}
 
Example 4
Source File: ServerImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void run() {
   LinkedList<HttpConnection> toClose = new LinkedList();
   ServerImpl.this.time = System.currentTimeMillis();
   ServerImpl.this.ticks++;
   synchronized(ServerImpl.this.idleConnections) {
      Iterator i$ = ServerImpl.this.idleConnections.iterator();

      HttpConnection c;
      while(i$.hasNext()) {
         c = (HttpConnection)i$.next();
         if (c.time <= ServerImpl.this.time) {
            toClose.add(c);
         }
      }

      i$ = toClose.iterator();

      while(i$.hasNext()) {
         c = (HttpConnection)i$.next();
         ServerImpl.this.idleConnections.remove(c);
         ServerImpl.this.allConnections.remove(c);
         c.close();
      }

   }
}
 
Example 5
Source File: HangChecker.java    From swift-k with Apache License 2.0 6 votes vote down vote up
private static boolean isSameCycle(LinkedList<Object> a, LinkedList<Object> b) {
    if (a.size() != b.size()) {
    	return false;
    }
    Iterator<Object> i = a.iterator();
    Object o = i.next();
    Iterator<Object> j = b.iterator();
    while (j.hasNext()) {
    	if (sameTraces(o, j.next())) {
    		while (i.hasNext()) {
    		    if (!j.hasNext()) {
    		        j = b.iterator();
    		    }
    		    if (!sameTraces(i.next(), j.next())) {
    		    	return false;
    		    }
    		}
    		return true;
    	}
    }
    return false;
}
 
Example 6
Source File: StringRange.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static LinkedList<Ranges> compact(int size, Set<Ranges> inputRanges) {
    LinkedList<Ranges> ranges = new LinkedList<Ranges>(inputRanges);
    for (int i = size-1; i >= 0; --i) {
        Ranges last = null;
        for (Iterator<Ranges> it = ranges.iterator(); it.hasNext();) {
            Ranges item = it.next();
            if (last == null) {
                last = item;
            } else if (last.merge(i, item)) {
                it.remove();
            } else {
                last = item; // go to next
            }
        }
    };
    return ranges;
}
 
Example 7
Source File: GcsUtil.java    From beam with Apache License 2.0 6 votes vote down vote up
List<BatchRequest> makeCopyBatches(LinkedList<RewriteOp> rewrites) throws IOException {
  List<BatchRequest> batches = new ArrayList<>();
  BatchRequest batch = createBatchRequest();
  Iterator<RewriteOp> it = rewrites.iterator();
  while (it.hasNext()) {
    RewriteOp rewrite = it.next();
    if (!rewrite.getReadyToEnqueue()) {
      it.remove();
      continue;
    }
    rewrite.enqueue(batch);

    if (batch.size() >= MAX_REQUESTS_PER_BATCH) {
      batches.add(batch);
      batch = createBatchRequest();
    }
  }
  if (batch.size() > 0) {
    batches.add(batch);
  }
  return batches;
}
 
Example 8
Source File: ReportPageReader.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
protected Long[] createEdges( long offset ) throws IOException
{
	LinkedList parents = new LinkedList( );
	IContent content = reader.loadContent( offset );
	while ( content != null )
	{
		DocumentExtension ext = (DocumentExtension) content
				.getExtension( IContent.DOCUMENT_EXTENSION );
		if ( ext != null )
		{
			parents.addFirst( new Long( ext.getIndex( ) ) );
		}
		content = (IContent) content.getParent( );
	}
	Long[] edges = new Long[parents.size( )];
	Iterator iter = parents.iterator( );
	int length = 0;
	while ( iter.hasNext( ) )
	{
		Long value = (Long) iter.next( );
		edges[length++] = value;
	}
	return edges;
}
 
Example 9
Source File: DefaultRegistry.java    From jpexs-decompiler with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void unregisterCodec(String codecClass) {
    for (Map.Entry<String, LinkedList<RegistryEntry>> i:codecMap.entrySet()) {
        LinkedList<RegistryEntry> ll=i.getValue();
        for (Iterator<RegistryEntry> j=ll.iterator();j.hasNext();) {
            RegistryEntry e=j.next();
            if (e.className.equals(codecClass)) {
                j.remove();
            }
        }
    }
}
 
Example 10
Source File: DatabaseMetaDataResultSet.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private Iterator<DatabaseMetaDataObject> initIterator(final ResultSet resultSet) throws SQLException {
    LinkedList<DatabaseMetaDataObject> result = new LinkedList<>();
    Set<DatabaseMetaDataObject> removeDuplicationSet = new HashSet<>();
    int tableNameColumnIndex = columnLabelIndexMap.getOrDefault(TABLE_NAME, -1);
    int indexNameColumnIndex = columnLabelIndexMap.getOrDefault(INDEX_NAME, -1);
    while (resultSet.next()) {
        DatabaseMetaDataObject databaseMetaDataObject = generateDatabaseMetaDataObject(tableNameColumnIndex, indexNameColumnIndex, resultSet);
        if (!removeDuplicationSet.contains(databaseMetaDataObject)) {
            result.add(databaseMetaDataObject);
            removeDuplicationSet.add(databaseMetaDataObject);
        }
    }
    return result.iterator();
}
 
Example 11
Source File: DynamicWebServiceInvoker.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Looks for the correct local method (i.e. not a web service operation proxy
 * method) on the Stub that matches the specified operationName and parms.
 * 
 * Operations with the most arguments will be matched first using all
 * specified parameters.
 * 
 * @param stub
 *          Axis Stub to execute
 * @param operationName
 *          name of the operation
 * @param stubInfo
 *          web service WSDL operation/parameter information
 * @param parms
 *          user specified parameters
 * @return results of searching for the web service operation
 */
private OperationSearchResult findMethod(Stub stub, String operationName, StubInfo stubInfo, cfWSParameter[] parms) {
	OperationSearchResult result = new OperationSearchResult();
	result.isWebServiceOperation = false;

	// Get all the methods with the correct name and order them by
	// number of parameters, descending.
	Method[] methods = stub.getClass().getMethods();
	LinkedList operations = new LinkedList();
	for (int i = 0; i < methods.length; i++) {
		if (methods[i].getName().equalsIgnoreCase(operationName))
			operations.add(methods[i]);
	}
	Collections.sort(operations, new Comparator() {
		public int compare(Object o1, Object o2) {
			return (((Method) o2).getParameterTypes().length - ((Method) o1).getParameterTypes().length);
		}
	});

	// Examine all the methods
	Iterator itr = operations.iterator();
	while (itr.hasNext()) {
		// Try to match up the parameters
		Method operation = (Method) itr.next();
		examineMethod(result, operation, parms);
		if (result.method != null)
			break;
	}

	return result;
}
 
Example 12
Source File: AdminEventEngine.java    From L2jBrasil with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
void killTeam(L2PcInstance activeChar, int team){
       LinkedList linked = L2Event.players.get(team);
       Iterator it = linked.iterator();
       while(it.hasNext()){
           try{L2PcInstance target = L2World.getInstance().getPlayer(it.next().toString());
           target.reduceCurrentHp(target.getMaxHp() + target.getMaxCp() + 1, activeChar);}catch(Exception e){}
       }

   }
 
Example 13
Source File: RxUtil.java    From likequanmintv with Apache License 2.0 5 votes vote down vote up
public static void cancelSubscriptions(LinkedList<Subscription> subscriptions) {
    Iterator<Subscription> iterator =
            subscriptions.iterator();

    while (iterator.hasNext()){
        Subscription subscription = iterator.next();
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }
}
 
Example 14
Source File: MaximallySpecific.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Given a list of methods, returns a list of maximally specific methods, applying language-runtime specific
 * conversion preferences.
 *
 * @param methods the list of methods
 * @param varArgs whether to assume the methods are varargs
 * @param argTypes concrete argument types for the invocation
 * @return the list of maximally specific methods.
 */
private static <T> List<T> getMaximallySpecificMethods(List<T> methods, boolean varArgs,
        Class<?>[] argTypes, LinkerServices ls, MethodTypeGetter<T> methodTypeGetter) {
    if(methods.size() < 2) {
        return methods;
    }
    final LinkedList<T> maximals = new LinkedList<>();
    for(T m: methods) {
        final MethodType methodType = methodTypeGetter.getMethodType(m);
        boolean lessSpecific = false;
        for(Iterator<T> maximal = maximals.iterator(); maximal.hasNext();) {
            final T max = maximal.next();
            switch(isMoreSpecific(methodType, methodTypeGetter.getMethodType(max), varArgs, argTypes, ls)) {
                case TYPE_1_BETTER: {
                    maximal.remove();
                    break;
                }
                case TYPE_2_BETTER: {
                    lessSpecific = true;
                    break;
                }
                case INDETERMINATE: {
                    // do nothing
                    break;
                }
                default: {
                    throw new AssertionError();
                }
            }
        }
        if(!lessSpecific) {
            maximals.addLast(m);
        }
    }
    return maximals;
}
 
Example 15
Source File: JsonParseUtils.java    From OpenEyes with Apache License 2.0 5 votes vote down vote up
public static List<FindMoreEntity> parseFromJson(String jsonData){
    List<FindMoreEntity> entities=new ArrayList<>();
    Type listType = new TypeToken<LinkedList<FindMoreEntity>>(){}.getType();
    Gson gson = new Gson();
    LinkedList<FindMoreEntity> findMoreEntities = gson.fromJson(jsonData, listType);
    for (Iterator iterator = findMoreEntities.iterator(); iterator.hasNext();) {
        FindMoreEntity findMoreEntity = (FindMoreEntity) iterator.next();
        entities.add(findMoreEntity);
    }
    return entities;
}
 
Example 16
Source File: Tabulator.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected Cell overlapParentCell(Cell existingCell, FrameCell currentParent)
{
	LinkedList<FrameCell> existingParents = new LinkedList<FrameCell>();
	for (FrameCell parent = existingCell.getParent(); parent != null; parent = parent.getParent())
	{
		existingParents.addFirst(parent);
	}
	
	LinkedList<FrameCell> currentParents = new LinkedList<FrameCell>();
	for (FrameCell parent = currentParent; parent != null; parent = parent.getParent())
	{
		currentParents.addFirst(parent);
	}
	
	Iterator<FrameCell> existingIt = existingParents.iterator();
	Iterator<FrameCell> currentIt = currentParents.iterator();
	while (existingIt.hasNext())
	{
		FrameCell existingParent = existingIt.next();
		FrameCell currentCell = currentIt.hasNext() ? currentIt.next() : null;
		if (currentCell == null || !existingParent.equals(currentCell))
		{
			return existingParent;
		}
	}
	
	return existingCell;
}
 
Example 17
Source File: MethodKey.java    From commons-jexl with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the most specific method that is applicable to actual argument types.<p>
 * Attempts to find the most specific applicable method using the
 * algorithm described in the JLS section 15.12.2 (with the exception that it can't
 * distinguish a primitive type argument from an object type argument, since in reflection
 * primitive type arguments are represented by their object counterparts, so for an argument of
 * type (say) java.lang.Integer, it will not be able to decide between a method that takes int and a
 * method that takes java.lang.Integer as a parameter.
 * </p>
 * <p>
 * This turns out to be a relatively rare case where this is needed - however, functionality
 * like this is needed.
 * </p>
 *
 * @param key a method key, esp its parameters
 * @param methods a list of methods
 * @return the most specific method.
 * @throws MethodKey.AmbiguousException if there is more than one.
 */
private T getMostSpecific(MethodKey key, T[] methods) {
    final Class<?>[] args = key.params;
    LinkedList<T> applicables = getApplicables(methods, args);
    if (applicables.isEmpty()) {
        return null;
    }

    if (applicables.size() == 1) {
        return applicables.getFirst();
    }

    /*
     * This list will contain the maximally specific methods. Hopefully at
     * the end of the below loop, the list will contain exactly one method,
     * (the most specific method) otherwise we have ambiguity.
     */
    LinkedList<T> maximals = new LinkedList<T>();
    for (T app : applicables) {
        final Class<?>[] parms = getParameterTypes(app);
        boolean lessSpecific = false;
        Iterator<T> maximal = maximals.iterator();
        while(!lessSpecific && maximal.hasNext()) {
            T max = maximal.next();
            switch (moreSpecific(args, parms, getParameterTypes(max))) {
                case MORE_SPECIFIC:
                    /*
                    * This method is more specific than the previously
                    * known maximally specific, so remove the old maximum.
                    */
                    maximal.remove();
                    break;

                case LESS_SPECIFIC:
                    /*
                    * This method is less specific than some of the
                    * currently known maximally specific methods, so we
                    * won't add it into the set of maximally specific
                    * methods
                    */

                    lessSpecific = true;
                    break;
                default:
                    // nothing do do
            }
        }

        if (!lessSpecific) {
            maximals.addLast(app);
        }
    }
    // if we have more than one maximally specific method, this call is ambiguous...
    if (maximals.size() > 1) {
        throw ambiguousException(args, applicables);
    }
    return maximals.getFirst();
}
 
Example 18
Source File: J_AbstractVerifier_V.java    From steady with Apache License 2.0 4 votes vote down vote up
public final void verify(final String host, final String[] cns,
                         final String[] subjectAlts,
                         final boolean strictWithSubDomains)
      throws SSLException {

    // Build the list of names we're going to check.  Our DEFAULT and
    // STRICT implementations of the HostnameVerifier only use the
    // first CN provided.  All other CNs are ignored.
    // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
    final LinkedList<String> names = new LinkedList<String>();
    if(cns != null && cns.length > 0 && cns[0] != null) {
        names.add(cns[0]);
    }
    if(subjectAlts != null) {
        for (final String subjectAlt : subjectAlts) {
            if (subjectAlt != null) {
                names.add(subjectAlt);
            }
        }
    }

    if(names.isEmpty()) {
        final String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
        throw new SSLException(msg);
    }

    // StringBuilder for building the error message.
    final StringBuilder buf = new StringBuilder();

    // We're can be case-insensitive when comparing the host we used to
    // establish the socket to the hostname in the certificate.
    final String hostName = normaliseIPv6Address(host.trim().toLowerCase(Locale.ENGLISH));
    boolean match = false;
    for(final Iterator<String> it = names.iterator(); it.hasNext();) {
        // Don't trim the CN, though!
        String cn = it.next();
        cn = cn.toLowerCase(Locale.ENGLISH);
        // Store CN in StringBuilder in case we need to report an error.
        buf.append(" <");
        buf.append(cn);
        buf.append('>');
        if(it.hasNext()) {
            buf.append(" OR");
        }

        // The CN better have at least two dots if it wants wildcard
        // action.  It also can't be [*.co.uk] or [*.co.jp] or
        // [*.org.uk], etc...
        final String parts[] = cn.split("\\.");
        final boolean doWildcard =
                parts.length >= 3 && parts[0].endsWith("*") &&
                validCountryWildcard(cn) && !isIPAddress(host);

        if(doWildcard) {
            final String firstpart = parts[0];
            if (firstpart.length() > 1) { // e.g. server*
                final String prefix = firstpart.substring(0, firstpart.length() - 1); // e.g. server
                final String suffix = cn.substring(firstpart.length()); // skip wildcard part from cn
                final String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host
                match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
            } else {
                match = hostName.endsWith(cn.substring(1));
            }
            if(match && strictWithSubDomains) {
                // If we're in strict mode, then [*.foo.com] is not
                // allowed to match [a.b.foo.com]
                match = countDots(hostName) == countDots(cn);
            }
        } else {
            match = hostName.equals(normaliseIPv6Address(cn));
        }
        if(match) {
            break;
        }
    }
    if(!match) {
        throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
    }
}
 
Example 19
Source File: AbstractVerifierDef.java    From steady with Apache License 2.0 4 votes vote down vote up
public final void verify(final String host, final String[] cns,
                         final String[] subjectAlts,
                         final boolean strictWithSubDomains)
      throws SSLException {

    // Build the list of names we're going to check.  Our DEFAULT and
    // STRICT implementations of the HostnameVerifier only use the
    // first CN provided.  All other CNs are ignored.
    // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
    final LinkedList<String> names = new LinkedList<String>();
    if(cns != null && cns.length > 0 && cns[0] != null) {
        names.add(cns[0]);
    }
    if(subjectAlts != null) {
        for (final String subjectAlt : subjectAlts) {
            if (subjectAlt != null) {
                names.add(subjectAlt);
            }
        }
    }

    if(names.isEmpty()) {
        final String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
        throw new SSLException(msg);
    }

    // StringBuilder for building the error message.
    final StringBuilder buf = new StringBuilder();

    // We're can be case-insensitive when comparing the host we used to
    // establish the socket to the hostname in the certificate.
    final String hostName = normaliseIPv6Address(host.trim().toLowerCase(Locale.ENGLISH));
    boolean match = false;
    for(final Iterator<String> it = names.iterator(); it.hasNext();) {
        // Don't trim the CN, though!
        String cn = it.next();
        cn = cn.toLowerCase(Locale.ENGLISH);
        // Store CN in StringBuilder in case we need to report an error.
        buf.append(" <");
        buf.append(cn);
        buf.append('>');
        if(it.hasNext()) {
            buf.append(" OR");
        }

        // The CN better have at least two dots if it wants wildcard
        // action.  It also can't be [*.co.uk] or [*.co.jp] or
        // [*.org.uk], etc...
        final String parts[] = cn.split("\\.");
        final boolean doWildcard =
                parts.length >= 3 && parts[0].endsWith("*") &&
                validCountryWildcard(cn) && !isIPAddress(host);

        if(doWildcard) {
            final String firstpart = parts[0];
            if (firstpart.length() > 1) { // e.g. server*
                final String prefix = firstpart.substring(0, firstpart.length() - 1); // e.g. server
                final String suffix = cn.substring(firstpart.length()); // skip wildcard part from cn
                final String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host
                match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
            } else {
                match = hostName.endsWith(cn.substring(1));
            }
            if(match && strictWithSubDomains) {
                // If we're in strict mode, then [*.foo.com] is not
                // allowed to match [a.b.foo.com]
                match = countDots(hostName) == countDots(cn);
            }
        } else {
            match = hostName.equals(normaliseIPv6Address(cn));
        }
        if(match) {
            break;
        }
    }
    if(!match) {
        throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
    }
}
 
Example 20
Source File: SaveTopologyinDB.java    From netphony-topology with Apache License 2.0 4 votes vote down vote up
/**
 * This function write a BGP4 update message in Data Base for each link in the list
 * @param intradomainLinks
 */
private void writeLinkDBInter(LinkedList<InterDomainEdge> interdomainLinks){
	
		Iterator<InterDomainEdge> edgeIt = interdomainLinks.iterator();
		
		while (edgeIt.hasNext()){

			InterDomainEdge edge = edgeIt.next();
			
			DatabaseControlSimplifiedLSA dcsl =createSimplifiedLSAInter(edge); 
			String jsonLSA = dcsl.logJsonSimplifiedLSA();
			//rdh.write("LSA:"+dcsl.getAdvertisingRouter().getHostAddress()+":"+dcsl.getLinkId().getHostAddress(),jsonLSA);		
			String ret = jedis.set("LSA:"+dcsl.getAdvertisingRouter().getHostAddress()+":"+dcsl.getLinkId().getHostAddress(), jsonLSA);
		}

}