Java Code Examples for java.util.NoSuchElementException

The following are top voted examples for showing how to use java.util.NoSuchElementException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: tikv-client-lib-java   File: CoprocessIterator.java   Source Code and License 7 votes vote down vote up
public static CoprocessIterator<Long> getHandleIterator(TiDAGRequest req,
                                                        List<RegionTask> regionTasks,
                                                        TiSession session) {
  return new DAGIterator<Long>(
      req.buildScan(true),
      regionTasks,
      session,
      SchemaInfer.create(req),
      req.getPushDownType()
  ) {
    @Override
    public Long next() {
      if (hasNext()) {
        return rowReader.readRow(handleTypes).getLong(0);
      } else {
        throw new NoSuchElementException();
      }
    }
  };
}
 
Example 2
Project: parabuild-ci   File: Result.java   Source Code and License 6 votes vote down vote up
public Object next() {

            if (hasNext()) {
                removed = false;

                if (counter != 0) {
                    last    = current;
                    current = current.next;
                }

                counter++;

                return current.data;
            }

            throw new NoSuchElementException();
        }
 
Example 3
Project: monarch   File: LinuxProcFsStatistics.java   Source Code and License 6 votes vote down vote up
private static void getLoadAvg(double[] doubles) {
  InputStreamReader isr = null;
  BufferedReader br = null;
  try {
    isr = new InputStreamReader(new FileInputStream("/proc/loadavg"));
    br = new BufferedReader(isr, 512);
    String line = br.readLine();
    if (line == null) {
      return;
    }
    st.setString(line);
    doubles[LinuxSystemStats.loadAverage1DOUBLE] = st.nextTokenAsDouble();
    doubles[LinuxSystemStats.loadAverage5DOUBLE] = st.nextTokenAsDouble();
    doubles[LinuxSystemStats.loadAverage15DOUBLE] = st.nextTokenAsDouble();
  } catch (NoSuchElementException nsee) {
  } catch (IOException ioe) {
  } finally {
    st.releaseResources();
    if (br != null)
      try {
        br.close();
      } catch (IOException ignore) {
      }
  }
}
 
Example 4
Project: scanning   File: RepeatedPointIterator.java   Source Code and License 6 votes vote down vote up
@Override
public IPosition next() {
	if (!hasNext()) {
		throw new NoSuchElementException();
	}

	if (model.getSleep()>0) {
		try {
			Thread.sleep(model.getSleep());
			if (countSleeps) sleepCount++;
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			throw new RuntimeException(e);
		}
	}
	Scalar<Double> point = new Scalar<>(model.getName(), count, model.getValue());
	count++;
	return point;
}
 
Example 5
Project: jmt   File: CircularEventQueue.java   Source Code and License 6 votes vote down vote up
/**
 * Returns an enumeration of the components of this vector. The
 * returned <tt>Enumeration</tt> object will generate all items in
 * this vector. The first item generated is the item at index <tt>0</tt>,
 * then the item at index <tt>1</tt>, and so on.
 *
 * @return  an enumeration of the components of this vector.
 * @see     Enumeration
 * @see     java.util.Iterator
 */
public Enumeration<SimEvent> elements() {
	return new Enumeration<SimEvent>() {
		int count = start;

		public boolean hasMoreElements() {
			return count < size;
		}

		public SimEvent nextElement() {
			synchronized (CircularEventQueue.this) {
				if (count < size) {
					return data[count++];
				}
			}
			throw new NoSuchElementException("Vector Enumeration");
		}
	};
}
 
Example 6
Project: hygene   File: MetadataParser.java   Source Code and License 6 votes vote down vote up
/**
 * Parses the metadata of a link (edge) to an {@link EdgeMetadata} object.
 *
 * @param gfa        string containing the contents of the GFA file
 * @param byteOffset the byte offset where the edge should be located
 * @return an {@link EdgeMetadata} object containing a link's metadata
 * @throws MetadataParseException if the GFA file or given line is invalid
 */
public EdgeMetadata parseEdgeMetadata(final GfaFile gfa, final long byteOffset) throws MetadataParseException {
    final String line = getLine(gfa.getRandomAccessFile(), byteOffset);

    validateLine(line, "L", byteOffset);

    final StringTokenizer st = initializeStringTokenizer(line, byteOffset);

    try {
        st.nextToken();
        st.nextToken();
        final String fromOrient = st.nextToken();
        st.nextToken();
        final String toOrient = st.nextToken();
        final String overlap = st.nextToken();

        return new EdgeMetadata(fromOrient, toOrient, overlap);
    } catch (final NoSuchElementException e) {
        throw new MetadataParseException("Not enough parameters for link at position " + byteOffset, e);
    }
}
 
Example 7
Project: mbed-cloud-sdk-java   File: APIMethod.java   Source Code and License 5 votes vote down vote up
private Object invokeMethod(Object moduleInstance, Map<String, Map<String, Object>> argsDescription)
        throws NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException, APICallException {
    if (moduleInstance == null) {
        throw new NoSuchElementException();
    }
    Method m = fetchMethod(moduleInstance.getClass());
    if (m == null) {
        throw new NoSuchMethodException();
    }
    Object[] args = fetchArgsValues(argsDescription);
    return (args == null) ? m.invoke(moduleInstance) : m.invoke(moduleInstance, args);
}
 
Example 8
Project: Ftc2018RelicRecovery   File: HalDashboard.java   Source Code and License 5 votes vote down vote up
/**
 * This method returns the value of the named double data read from the Telemetry class. If the named data does
 * not exist, it is created and assigned the given default value. Then it is sent to the Driver Station.
 *
 * @param key specifies the name associated with the double data.
 * @param defaultValue specifies the default value if it does not exist.
 * @return double data value.
 */
public double getNumber(String key, double defaultValue)
{
    final String funcName = "getNumber";
    double value;

    if (debugEnabled)
    {
        dbgTrace.traceEnter(funcName, TrcDbgTrace.TraceLevel.API, "key=%s,defValue=%f", key, defaultValue);
    }

    try
    {
        value = getNumber(key);
    }
    catch (NoSuchElementException e)
    {
        putNumber(key, defaultValue);
        value = defaultValue;
    }

    if (debugEnabled)
    {
        dbgTrace.traceExit(funcName, TrcDbgTrace.TraceLevel.API, "=%f", value);
    }

    return value;
}
 
Example 9
Project: HL4A   File: NativeTypedArrayIterator.java   Source Code and License 5 votes vote down vote up
@Override
public T next()
{
    if (hasNext()) {
        T ret = (T)view.get(position);
        lastPosition = position;
        position++;
        return ret;
    }
    throw new NoSuchElementException();
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: FairBlockingQueue.java   Source Code and License 5 votes vote down vote up
@Override
public E next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    element = elements[index++];
    return element;
}
 
Example 11
Project: googles-monorepo-demo   File: TreeRangeMapTest.java   Source Code and License 5 votes vote down vote up
public void testSpanTwoRanges() {
  for (Range<Integer> range1 : RANGES) {
    for (Range<Integer> range2 : RANGES) {
      RangeMap<Integer, Integer> rangeMap = TreeRangeMap.create();
      rangeMap.put(range1, 1);
      rangeMap.put(range2, 2);

      Range<Integer> expected;
      if (range1.isEmpty()) {
        if (range2.isEmpty()) {
          expected = null;
        } else {
          expected = range2;
        }
      } else {
        if (range2.isEmpty()) {
          expected = range1;
        } else {
          expected = range1.span(range2);
        }
      }

      try {
        assertEquals(expected, rangeMap.span());
        assertNotNull(expected);
      } catch (NoSuchElementException e) {
        assertNull(expected);
      }
    }
  }
}
 
Example 12
Project: practical-functional-java   File: OptionalTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testOptionalMapOnEmpty() {
    Optional<String> emptyName = Optional.empty();  // or Optional.ofNullable(null);
    
    Optional<String> emptyUpperName = emptyName.map(String::toUpperCase);
    
    assertThat(emptyUpperName.isPresent()).isFalse();
    
    try {
        assertThat(emptyUpperName.get()).isEqualTo("FRED");
        fail("found a value on an empty Optional");
    } catch (NoSuchElementException e) {
        // ignore
    }
}
 
Example 13
Project: luna   File: Code.java   Source Code and License 5 votes vote down vote up
public BasicBlock block(Label label) {
  Objects.requireNonNull(label);
  BasicBlock result = index.get(label);
  if (result != null) {
    return result;
  } else {
    throw new NoSuchElementException("Label not found: " + label);
  }
}
 
Example 14
Project: javaide   File: MixedItemSection.java   Source Code and License 5 votes vote down vote up
/**
 * Gets an item which was previously interned.
 *
 * @param item {@code non-null;} the item to look for
 * @return {@code non-null;} the equivalent already-interned instance
 */
public <T extends OffsettedItem> T get(T item) {
    throwIfNotPrepared();

    OffsettedItem result = interns.get(item);

    if (result != null) {
        return (T) result;
    }

    throw new NoSuchElementException(item.toString());
}
 
Example 15
Project: chromium-for-android-56-debug-video   File: CustomTabsService.java   Source Code and License 5 votes vote down vote up
/**
 * Called when the client side {@link IBinder} for this {@link CustomTabsSessionToken} is dead.
 * Can also be used to clean up {@link DeathRecipient} instances allocated for the given token.
 * @param sessionToken The session token for which the {@link DeathRecipient} call has been
 *                     received.
 * @return Whether the clean up was successful. Multiple calls with two tokens holdings the
 *         same binder will return false.
 */
protected boolean cleanUpSession(CustomTabsSessionToken sessionToken) {
    try {
        synchronized (mDeathRecipientMap) {
           IBinder binder = sessionToken.getCallbackBinder();
           DeathRecipient deathRecipient =
                   mDeathRecipientMap.get(binder);
           binder.unlinkToDeath(deathRecipient, 0);
           mDeathRecipientMap.remove(binder);
       }
    } catch (NoSuchElementException e) {
        return false;
    }
    return true;
}
 
Example 16
Project: ctsms   File: EcrfRowProcessor.java   Source Code and License 5 votes vote down vote up
private Long getVisitId(String visitToken) throws Exception {
	Long visitId = null;
	if (!CommonUtil.isEmptyString(visitToken)) {
		if (!visitIdMap.containsKey(visitToken)) {
			try {
				visitId = visitDao.findByTrialTitleToken(context.getEntityId(), null, visitToken).iterator().next().getId();
			} catch (NoSuchElementException e) {
				VisitOutVO visitVO = createVisit(visitToken);
				visitId = visitVO.getId();
				jobOutput.println("visit '" + visitVO.getUniqueName() + "' created");
			}
			visitIdMap.put(visitToken, visitId);
		} else {
			visitId = visitIdMap.get(visitToken);
		}
	}
	return visitId;
}
 
Example 17
Project: RxJava3-preview   File: FlowableFirstTest.java   Source Code and License 5 votes vote down vote up
@Test
public void firstOrErrorNoElement() {
    Flowable.empty()
        .firstOrError()
        .test()
        .assertNoValues()
        .assertError(NoSuchElementException.class);
}
 
Example 18
Project: JRediClients   File: Pool.java   Source Code and License 5 votes vote down vote up
public T getResource() {
	try {
		return internalPool.borrowObject();
	} catch (NoSuchElementException nse) {
		if (null == nse.getCause()) { // The exception was caused by an exhausted pool
			throw new JedisExhaustedPoolException("Could not get a resource since the pool is exhausted", nse);
		}
		// Otherwise, the exception was caused by the implemented activateObject() or
		// ValidateObject()
		throw new JedisException("Could not get a resource from the pool", nse);
	} catch (Exception e) {
		throw new JedisConnectionException("Could not get a resource from the pool", e);
	}
}
 
Example 19
Project: guava-mock   File: IteratorsTest.java   Source Code and License 5 votes vote down vote up
public void testFind_notPresent() {
  Iterable<String> list = Lists.newArrayList("cool", "pants");
  Iterator<String> iterator = list.iterator();
  try {
    Iterators.find(iterator, Predicates.alwaysFalse());
    fail();
  } catch (NoSuchElementException e) {
  }
  assertFalse(iterator.hasNext());
}
 
Example 20
Project: Elasticsearch   File: BackoffPolicy.java   Source Code and License 5 votes vote down vote up
@Override
public TimeValue next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    curr++;
    return delay;
}
 
Example 21
Project: luna   File: TypeInfo.java   Source Code and License 5 votes vote down vote up
public boolean isReified(Var v) {
  Objects.requireNonNull(v);

  Boolean r = vars.get(v);
  if (r != null) {
    return r.booleanValue();
  } else {
    throw new NoSuchElementException("Variable not found: " + v);
  }
}
 
Example 22
Project: Logisim   File: IteratorUtil.java   Source Code and License 5 votes vote down vote up
@Override
public E next() {
	if (taken)
		throw new NoSuchElementException();
	taken = true;
	return data;
}
 
Example 23
Project: monix-forkjoin   File: LinkedTransferQueue.java   Source Code and License 5 votes vote down vote up
public final E next() {
    Node p = nextNode;
    if (p == null) throw new NoSuchElementException();
    E e = nextItem;
    advance(p);
    return e;
}
 
Example 24
Project: incubator-netbeans   File: ProxyHighlightsContainer.java   Source Code and License 5 votes vote down vote up
public @Override int getStartOffset() {
    synchronized (ProxyHighlightsContainer.this.LOCK) {
        if (index1 == -2 && index2 == -2) {
            throw new IllegalStateException("Uninitialized sequence, call moveNext() first."); //NOI18N
        } else if (index1 == -1 || index2 == -1) {
            throw new NoSuchElementException();
        }

        return marks[index1].getPreviousMarkOffset();
    }
}
 
Example 25
Project: CraftoDB   File: Row.java   Source Code and License 5 votes vote down vote up
/** TODO: Documentation */
public double getDouble(String columnName) throws NoSuchColumnException, NoSuchElementException {
	DBUtil.notNullNotEmpty(columnName, "The columnName must neither be null nor empty: " + columnName);

	Object object = this.pull(columnName);
	if (object == null) { throw new NoSuchElementException("Column has null value: " + columnName); }
	return Double.parseDouble(object.toString());
}
 
Example 26
Project: incubator-netbeans   File: SimpleSearchIterator.java   Source Code and License 5 votes vote down vote up
/**
 */
@Override
public FileObject next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }

    upToDate = false;
    return nextObject;
}
 
Example 27
Project: chipKIT-importer   File: ChipKitImportWizardIterator.java   Source Code and License 5 votes vote down vote up
@Override
public void nextPanel() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    index++;
}
 
Example 28
Project: mupdf-android-viewer-old   File: ArrayDeque.java   Source Code and License 5 votes vote down vote up
/**
 * @throws NoSuchElementException {@inheritDoc}
 */
public E getLast() {
	@SuppressWarnings("unchecked")
	E result = (E) elements[(tail - 1) & (elements.length - 1)];
	if (result == null)
		throw new NoSuchElementException();
	return result;
}
 
Example 29
Project: googles-monorepo-demo   File: QueueRemoveTester.java   Source Code and License 5 votes vote down vote up
@CollectionFeature.Require(SUPPORTS_REMOVE)
@CollectionSize.Require(ZERO)
public void testRemove_empty() {
  try {
    getQueue().remove();
    fail("emptyQueue.remove() should throw");
  } catch (NoSuchElementException expected) {
  }
  expectUnchanged();
}
 
Example 30
Project: rskj   File: RskWireProtocol.java   Source Code and License 5 votes vote down vote up
/*************************
 *  Message Processing   *
 *************************/

protected void processStatus(org.ethereum.net.eth.message.StatusMessage msg, ChannelHandlerContext ctx) throws InterruptedException {

    try {
        Genesis genesis = GenesisLoader.loadGenesis(config, config.genesisInfo(), config.getBlockchainConfig().getCommonConstants().getInitialNonce(), true);
        if (!Arrays.equals(msg.getGenesisHash(), genesis.getHash())
                || msg.getProtocolVersion() != version.getCode()) {
            loggerNet.info("Removing EthHandler for {} due to protocol incompatibility", ctx.channel().remoteAddress());
            ethState = EthState.STATUS_FAILED;
            recordEvent(EventType.INCOMPATIBLE_PROTOCOL);
            disconnect(ReasonCode.INCOMPATIBLE_PROTOCOL);
            ctx.pipeline().remove(this); // Peer is not compatible for the 'eth' sub-protocol
            return;
        }

        if (msg.getNetworkId() != config.networkId()) {
            ethState = EthState.STATUS_FAILED;
            recordEvent(EventType.INVALID_NETWORK);
            disconnect(ReasonCode.NULL_IDENTITY);
            return;
        }

        // basic checks passed, update statistics
        channel.getNodeStatistics().ethHandshake(msg);
        ethereumListener.onEthStatusUpdated(channel, msg);

        if (peerDiscoveryMode) {
            loggerNet.debug("Peer discovery mode: STATUS received, disconnecting...");
            disconnect(ReasonCode.REQUESTED);
            ctx.close().sync();
            ctx.disconnect().sync();
            return;
        }
    } catch (NoSuchElementException e) {
        loggerNet.debug("EthHandler already removed");
    }
}
 
Example 31
Project: Java-Algorithms-Learning   File: DoubleLinkedList.java   Source Code and License 5 votes vote down vote up
/**
 * 返回List前端的元素, 并把该元素从List中删除.(模拟LIFO)
 * @throws NoSuchElementException
 * if the client attempts to remove an item from an empty list
 * @return List前端第一个元素
 */
public Item popFirst() {
    if (getSize() == 0)
        throw new NoSuchElementException("This DoubleLinkedList is empty!");

    return pop(0);
}
 
Example 32
Project: guava-mock   File: MinMaxPriorityQueue.java   Source Code and License 5 votes vote down vote up
/**
 * Removes and returns the greatest element of this queue.
 *
 * @throws NoSuchElementException if the queue is empty
 */
@CanIgnoreReturnValue
public E removeLast() {
  if (isEmpty()) {
    throw new NoSuchElementException();
  }
  return removeAndGet(getMaxElementIndex());
}
 
Example 33
Project: googles-monorepo-demo   File: SortedSetNavigationTester.java   Source Code and License 5 votes vote down vote up
@CollectionSize.Require(ZERO)
public void testEmptySetLast() {
  try {
    sortedSet.last();
    fail();
  } catch (NoSuchElementException e) {
  }
}
 
Example 34
Project: ChronoBike   File: CMove.java   Source Code and License 5 votes vote down vote up
protected Element ExportCustom(Document root)
{
	Element eMove ;
	if (m_bMoveCorresponding)
	{
		eMove = root.createElement("MoveCorresponding") ;
	}
	else
	{
		eMove = root.createElement("Move") ;
	}
	Element eFrom = root.createElement("From") ;
	m_valueFrom.ExportTo(eFrom, root) ;
	eMove.appendChild(eFrom) ;
	ListIterator i = m_arrToIdentifiers.listIterator() ;
	try
	{
		CIdentifier idDest = (CIdentifier)i.next() ;
		while (idDest != null)
		{
			Element dest ;
			if (m_bFillAll)
			{
				dest = root.createElement("Fill") ;
			}
			else
			{
				dest = root.createElement("To") ;
			}
			idDest.ExportTo(dest, root) ;
			eMove.appendChild(dest) ;
			idDest = (CIdentifier)i.next() ;
		}
	}
	catch (NoSuchElementException e)
	{
		// nothing 
	}
	return eMove;
}
 
Example 35
Project: guava-mock   File: AbstractNavigableMap.java   Source Code and License 5 votes vote down vote up
@Override
public K lastKey() {
  Entry<K, V> entry = lastEntry();
  if (entry == null) {
    throw new NoSuchElementException();
  } else {
    return entry.getKey();
  }
}
 
Example 36
Project: mupdf-android-viewer-old   File: ArrayDeque.java   Source Code and License 5 votes vote down vote up
public E next() {
	if (cursor == fence)
		throw new NoSuchElementException();
	@SuppressWarnings("unchecked") E result = (E) elements[cursor];
	// This check doesn't catch all possible comodifications,
	// but does catch the ones that corrupt traversal
	if (tail != fence || result == null)
		throw new ConcurrentModificationException();
	lastRet = cursor;
	cursor = (cursor + 1) & (elements.length - 1);
	return result;
}
 
Example 37
Project: ditb   File: RowResultGenerator.java   Source Code and License 5 votes vote down vote up
public Cell next() {
  if (cache != null) {
    Cell kv = cache;
    cache = null;
    return kv;
  }
  if (valuesI == null) {
    return null;
  }
  try {
    return valuesI.next();
  } catch (NoSuchElementException e) {
    return null;
  }
}
 
Example 38
Project: openjdk-jdk10   File: ConcurrentLinkedQueue.java   Source Code and License 5 votes vote down vote up
public E next() {
    final Node<E> pred = nextNode;
    if (pred == null) throw new NoSuchElementException();
    // assert nextItem != null;
    lastRet = pred;
    E item = null;

    for (Node<E> p = succ(pred), q;; p = q) {
        if (p == null || (item = p.item) != null) {
            nextNode = p;
            E x = nextItem;
            nextItem = item;
            return x;
        }
        // unlink deleted nodes
        if ((q = succ(p)) != null)
            NEXT.compareAndSet(pred, p, q);
    }
}
 
Example 39
Project: OpenJSharp   File: NameImpl.java   Source Code and License 5 votes vote down vote up
public boolean addAll(Enumeration<String> comps) throws InvalidNameException {
    boolean added = false;
    while (comps.hasMoreElements()) {
        try {
            String comp = comps.nextElement();
            if (size() > 0 && syntaxDirection == FLAT) {
                throw new InvalidNameException(
                    "A flat name can only have a single component");
            }
            components.addElement(comp);
            added = true;
        } catch (NoSuchElementException e) {
            break;  // "comps" has shrunk.
        }
    }
    return added;
}
 
Example 40
Project: presto-manager   File: AgentFileUtils.java   Source Code and License 5 votes vote down vote up
public static String getFileProperty(Path path, String property)
        throws IOException
{
    Properties properties = new Properties();
    try (InputStream inputStream = new FileInputStream(path.toString())) {
        properties.load(inputStream);
    }
    if (!properties.containsKey(property)) {
        throw new NoSuchElementException("Property does not exist");
    }
    return properties.getProperty(property);
}
 
Example 41
Project: urule   File: DatabaseRecordIterator.java   Source Code and License 5 votes vote down vote up
/**
 * Return the next record. If there are no more records, throws
 * a <code>NoSuchElementException</code>. If an error occurs,
 * throws a <code>JournalException</code>.
 *
 * @return next record
 * @throws java.util.NoSuchElementException if there are no more records
 * @throws JournalException if another error occurs
 */
public Record nextRecord() throws NoSuchElementException, JournalException {
    if (!hasNext()) {
        String msg = "No current record.";
        throw new NoSuchElementException(msg);
    }
    close(lastRecord);
    lastRecord = record;
    record = null;

    return lastRecord;
}
 
Example 42
Project: jsf-sdk   File: UnpackerIterator.java   Source Code and License 5 votes vote down vote up
public Value next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    Value v = uc.getResult();
    uc.resetResult();
    return v;
}
 
Example 43
Project: googles-monorepo-demo   File: Iterables.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the last element of {@code iterable}. If {@code iterable} is a {@link List} with
 * {@link RandomAccess} support, then this operation is guaranteed to be {@code O(1)}.
 *
 * <p><b>{@code Stream} equivalent:</b> {@link Streams#findLast Streams.findLast(stream).get()}
 *
 * @return the last element of {@code iterable}
 * @throws NoSuchElementException if the iterable is empty
 */
public static <T> T getLast(Iterable<T> iterable) {
  // TODO(kevinb): Support a concurrently modified collection?
  if (iterable instanceof List) {
    List<T> list = (List<T>) iterable;
    if (list.isEmpty()) {
      throw new NoSuchElementException();
    }
    return getLastInNonemptyList(list);
  }

  return Iterators.getLast(iterable.iterator());
}
 
Example 44
Project: intermediateProgramming   File: MinhaBST.java   Source Code and License 5 votes vote down vote up
public Key floor(Key key) {
    if (key == null) throw new IllegalArgumentException("argument to floor() is null");
    if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table");
    Node x = floor(root, key);
    if (x == null) return null;
    else return x.key;
}
 
Example 45
Project: che-starter   File: StackClient.java   Source Code and License 5 votes vote down vote up
/**
 * Gets image for specified stack ID. Throws StackNotFoundException if there is no such stack
 * on the Che server.
 * 
 * @param cheServerUrl URL of Che server
 * @param stackId stack ID
 * @param keycloakToken Keycloak token
 * @return image name for stack
 * @throws StackNotFoundException if no image name exists for such stack ID or call to Che server was not successful
 */
public Stack getStack(String cheServerUrl, String stackId, String keycloakToken) throws StackNotFoundException {
    List<Stack> stacks = listStacks(cheServerUrl, keycloakToken);
    if (stacks != null && !stacks.isEmpty()) {
        try {
            Stack stack = stacks.stream().filter(s -> stackId.equals(s.getId())).findFirst().get();
            return stack;
        } catch (NoSuchElementException e) {
            throw new StackNotFoundException("Stack with id '" + stackId + "' was not found");
        }
    } else {
        throw new StackNotFoundException("No stacks were returned from Che server");
    }
}
 
Example 46
Project: lams   File: SecureHashMap.java   Source Code and License 5 votes vote down vote up
public Item<K, V> next() {
    if (hasNext()) try {
        return next;
    } finally {
        remove = next;
        next = null;
    }
    throw new NoSuchElementException();
}
 
Example 47
Project: tomcat7   File: MultiLockFairBlockingQueue.java   Source Code and License 5 votes vote down vote up
@Override
public E next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    }
    element = elements[index++];
    return element;
}
 
Example 48
Project: jdk8u-jdk   File: SmallSet.java   Source Code and License 5 votes vote down vote up
public E next() {
    if (e1 == null) {
        throw new NoSuchElementException();
    }
    E e = e1;
    e1 = e2;
    e2 = null;
    return e;
}
 
Example 49
Project: odoo-work   File: LinkedHashTreeMap.java   Source Code and License 5 votes vote down vote up
final Node<K, V> nextNode() {
  Node<K, V> e = next;
  if (e == header) {
    throw new NoSuchElementException();
  }
  if (modCount != expectedModCount) {
    throw new ConcurrentModificationException();
  }
  next = e.next;
  return lastReturned = e;
}
 
Example 50
Project: scanning   File: ExperimentConfiguration.java   Source Code and License 5 votes vote down vote up
public int getLocalValueIndex(IQueueValue<?> value) throws QueueModelException {
	OptionalInt indexOpt = IntStream.range(0, localValues.size()).filter(i -> value.equals(localValues.get(i))).findFirst();
	try {
		return indexOpt.getAsInt();
	} catch (NoSuchElementException nseEx) {
		throw new QueueModelException(nseEx);
	}
}
 
Example 51
Project: imputedb   File: LogicalPlan.java   Source Code and License 5 votes vote down vote up
/** Given a name of a field, try to figure out what table it belongs to by looking
     *   through all of the tables added via {@link #addScan}. 
     *  @return A fully qualified name of the form tableAlias.name.  If the name parameter is already qualified
     *   with a table name, simply returns name.
     *  @throws ParsingException if the field cannot be found in any of the tables, or if the
     *   field is ambiguous (appears in multiple tables)
     */
    private QualifiedName disambiguateName(String name) throws ParsingException {
        String[] fields = name.split("[.]");
        if (fields.length == 2 && (!fields[0].equals("null")))
            return new QualifiedName(fields[0], fields[1]);
        if (fields.length > 2) 
            throw new ParsingException("Field " + name + " is not a valid field reference.");
        if (fields.length == 2)
            name = fields[1];
        if (name.equals("*")) return new QualifiedName("null", name);
        //now look for occurrences of name in all of the tables
        Iterator<LogicalScanNode> tableIt = tables.iterator();
        String tableName = null;
        while (tableIt.hasNext()) {
            LogicalScanNode table = tableIt.next();
            try {
                TupleDesc td = Database.getCatalog().getDatabaseFile(table.t).getTupleDesc();
//                int id = 
                  td.fieldNameToIndex(name);
                if (tableName == null) {
                    tableName = table.alias;
                } else {
                    throw new ParsingException("Field " + name + " appears in multiple tables; disambiguate by referring to it as tablename." + name);
                }
            } catch (NoSuchElementException e) {
                //ignore
            }
        }
        if (tableName != null)
            return new QualifiedName(tableName, name);
        else
            throw new ParsingException("Field " + name + " does not appear in any tables.");

    }
 
Example 52
Project: RxDataBinding   File: RecordingObserver.java   Source Code and License 5 votes vote down vote up
private <E> E takeEvent(Class<E> wanted) {
  Object event;
  try {
    event = events.pollFirst(1, TimeUnit.SECONDS);
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
  if (event == null) {
    throw new NoSuchElementException(
        "No event found while waiting for " + wanted.getSimpleName());
  }
  assertTrue(wanted.isInstance(event));
  return wanted.cast(event);
}
 
Example 53
Project: sepatools   File: Engine.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws MalformedObjectNameException, InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException, FileNotFoundException, NoSuchElementException, IOException {
	System.out.println("##########################################################################################");
	System.out.println("# SEPA Engine Ver 0.6  Copyright (C) 2016-2017                                           #");
	System.out.println("# University of Bologna (Italy)                                                          #");
	System.out.println("#                                                                                        #");
	System.out.println("# This program comes with ABSOLUTELY NO WARRANTY                                         #");                                    
	System.out.println("# This is free software, and you are welcome to redistribute it under certain conditions #");
	System.out.println("# GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007                                    #");
	System.out.println("#                                                                                        #");
	System.out.println("# GitHub: https://github.com/vaimee/sepatools                                            #");
	System.out.println("# Web: http://wot.arces.unibo.it                                                         #");
	System.out.println("##########################################################################################");
	System.out.println("");		
	System.out.println("Dependencies");
	System.out.println("com.google.code.gson          2.8.0       Apache 2.0");
	System.out.println("com.nimbusds                  4.34.2      The Apache Software License, Version 2.0");
	System.out.println("commons-io                    2.5         Apache License, Version 2.0");
	System.out.println("commons-logging               1.2         The Apache Software License, Version 2.0");
	System.out.println("org.apache.httpcomponents     4.5.3       Apache License, Version 2.0");
	System.out.println("org.apache.httpcomponents     4.4.6       Apache License, Version 2.0");
	System.out.println("org.apache.logging.log4j      2.8.1       Apache License, Version 2.0");
	System.out.println("org.bouncycastle              1.56        Bouncy Castle Licence");
	System.out.println("org.eclipse.paho              1.1.1       Eclipse Public License - Version 1.0");
	System.out.println("org.glassfish.grizzly         2.3.30      CDDL+GPL");
	System.out.println("org.glassfish.tyrus.bundles   1.13.1      Dual license consisting of the CDDL v1.1 and GPL v2");
	System.out.println("org.jdom                      2.0.6       Similar to Apache License but with the acknowledgment clause removed");
	System.out.println("");
	
	//Engine creation and initialization
	Engine engine = new Engine();
	engine.init();
	
	//Starting main engine thread
	engine.start();
}
 
Example 54
Project: HCFCore   File: AbstractLinkedMap.java   Source Code and License 5 votes vote down vote up
protected LinkEntry<K, V> nextEntry() {
    if (parent.modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    if (next == parent.header)  {
        throw new NoSuchElementException(AbstractHashedMap.NO_NEXT_ENTRY);
    }
    last = next;
    next = next.after;
    return last;
}
 
Example 55
Project: tg-eventstore   File: EventShovel.java   Source Code and License 5 votes vote down vote up
private static <T> Iterator<Iterator<T>> batchBy(Iterator<T> it, Function<T, Object> grouping) {
    return new Iterator<Iterator<T>>() {
        PeekingIterator<T> peekingIterator = peekingIterator(it);

        @Override
        public boolean hasNext() {
            return peekingIterator.hasNext();
        }

        @Override
        public Iterator<T> next() {
            return new Iterator<T>() {
                private Object currentGroup = grouping.apply(peekingIterator.peek());

                private boolean isSameGroup() {
                    return currentGroup.equals(grouping.apply(peekingIterator.peek()));
                }

                @Override
                public boolean hasNext() {
                    return peekingIterator.hasNext() && isSameGroup();
                }

                @Override
                public T next() {
                    if (!isSameGroup()) {
                        throw new NoSuchElementException();
                    }
                    return peekingIterator.next();
                }
            };
        }
    };
}
 
Example 56
Project: Tarski   File: LinkedStack.java   Source Code and License 5 votes vote down vote up
/**
 * Iterates over the items in this LinkedStack, starting
 * at the top of the stack and working its way down.
 * @return iterator over the elements in this stack.
 */
public Iterator<T> iterator() {
	return new Iterator<T>() {
		private StackEntry<T> cursor = head, prev = null, pprev = null;
		public boolean hasNext() {
			return cursor != null;
		}

		public T next() {
			if (cursor==null) throw new NoSuchElementException();
			pprev = prev;
			prev = cursor;
			cursor = cursor.next;
			return prev.data;
		}

		public void remove() {
			if (prev==pprev) {
				throw new UnsupportedOperationException();
			} else if (prev==head) {
				head = cursor;
			} else {
				pprev.next = cursor;
				prev.next = null;
			}
			prev = pprev;
			size--;
		}
		
	};
}
 
Example 57
Project: guava-mock   File: SortedSetNavigationTester.java   Source Code and License 5 votes vote down vote up
@CollectionSize.Require(ZERO)
public void testEmptySetLast() {
  try {
    sortedSet.last();
    fail();
  } catch (NoSuchElementException e) {
  }
}
 
Example 58
Project: parabuild-ci   File: BaseHashMap.java   Source Code and License 5 votes vote down vote up
public int getAccessCount() {

            if (removed || accessTable == null) {
                throw new NoSuchElementException();
            }

            return accessTable[lookup];
        }
 
Example 59
Project: gw4e.project   File: BuildPolicyManager.java   Source Code and License 5 votes vote down vote up
/**
 * Load the build policies
 * 
 * @param projectName
 * @param resource
 * @param value
 * @return
 * @throws BuildPolicyConfigurationException
 */
public static List<BuildPolicy> getPolicies(String projectName, IFile buildPolicyFile, IFile graphModel,
		String listOfGenerators) throws BuildPolicyConfigurationException {
	List<BuildPolicy> ret = new ArrayList<BuildPolicy>();
	StringTokenizer st = new StringTokenizer(listOfGenerators.trim(), ";");
	String pathGenerator = null;
	String severity = null;
	while (st.hasMoreTokens()) {
		try {
			pathGenerator = (String) st.nextToken();
			severity = (String) st.nextToken();
			BuildPolicy bp = new BuildPolicy(projectName, buildPolicyFile, graphModel, pathGenerator, severity);
			ret.add(bp);
		} catch (NoSuchElementException e) {
			ParserContextProperties p = new ParserContextProperties();
			p.setProperty(SeverityConfigurationException.GRAPHMODELPATH, graphModel.getFullPath().toString());
			p.setProperty(SeverityConfigurationException.SEVERITY, String.valueOf(pathGenerator));
			p.setProperty(SeverityConfigurationException.PATH_GENERATOR, pathGenerator);
			p.setProperty(SeverityConfigurationException.BUILDPOLICIESPATH,
					buildPolicyFile.getFullPath().toString());
			Location location = ResourceManager.locationOfKeyValue(buildPolicyFile, graphModel.getName(),
					pathGenerator + ";" + severity);
			location.relocateAtLastChar();

			throw new SeverityConfigurationException(location, "Missing severity flag for '" + pathGenerator + "'",
					p);
		}
	}
	return ret;
}
 
Example 60
Project: OpenJSharp   File: PrefixArray.java   Source Code and License 5 votes vote down vote up
public final Iterator getPrefixes() {
    return new Iterator() {
        int _position = 1;
        NamespaceEntry _ne = _inScopeNamespaces[_position];

        public boolean hasNext() {
            return _ne != null;
        }

        public Object next() {
            if (_position == _size + 2) {
                throw new NoSuchElementException();
            }

            final String prefix = _ne.prefix;
            moveToNext();
            return prefix;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

        private final void moveToNext() {
            while (++_position < _size + 2) {
                _ne = _inScopeNamespaces[_position];
                if (_ne != null) {
                    return;
                }
            }
            _ne = null;
        }

    };
}