Java Code Examples for java.util.NoSuchElementException

The following examples show how to use java.util.NoSuchElementException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Strata   Author: OpenGamma   File: SwaptionSurfaceExpiryTenorParameterMetadata.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Builder set(String propertyName, Object newValue) {
  switch (propertyName.hashCode()) {
    case -1731780257:  // yearFraction
      this.yearFraction = (Double) newValue;
      break;
    case 110246592:  // tenor
      this.tenor = (Double) newValue;
      break;
    case 102727412:  // label
      this.label = (String) newValue;
      break;
    default:
      throw new NoSuchElementException("Unknown property: " + propertyName);
  }
  return this;
}
 
Example #2
Source Project: Strata   Author: OpenGamma   File: CrossGammaParameterSensitivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object get(String propertyName) {
  switch (propertyName.hashCode()) {
    case 842855857:  // marketDataName
      return marketDataName;
    case -1169106440:  // parameterMetadata
      return parameterMetadata;
    case 106006350:  // order
      return order;
    case 575402001:  // currency
      return currency;
    case 564403871:  // sensitivity
      return sensitivity;
    default:
      throw new NoSuchElementException("Unknown property: " + propertyName);
  }
}
 
Example #3
Source Project: android_9.0.0_r45   Author: lulululbj   File: TelephonyRegistry.java    License: Apache License 2.0 6 votes vote down vote up
private void remove(IBinder binder) {
    synchronized (mRecords) {
        final int recordCount = mRecords.size();
        for (int i = 0; i < recordCount; i++) {
            Record r = mRecords.get(i);
            if (r.binder == binder) {
                if (DBG) {
                    log("remove: binder=" + binder + " r.callingPackage " + r.callingPackage
                            + " r.callback " + r.callback);
                }

                if (r.deathRecipient != null) {
                    try {
                        binder.unlinkToDeath(r.deathRecipient, 0);
                    } catch (NoSuchElementException e) {
                        if (VDBG) log("UnlinkToDeath NoSuchElementException sending to r="
                                + r + " e=" + e);
                    }
                }

                mRecords.remove(i);
                return;
            }
        }
    }
}
 
Example #4
Source Project: Strata   Author: OpenGamma   File: KnownAmountBondPaymentPeriod.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object get(String propertyName) {
  switch (propertyName.hashCode()) {
    case -786681338:  // payment
      return payment;
    case -2129778896:  // startDate
      return startDate;
    case -1607727319:  // endDate
      return endDate;
    case 1457691881:  // unadjustedStartDate
      return unadjustedStartDate;
    case 31758114:  // unadjustedEndDate
      return unadjustedEndDate;
    default:
      throw new NoSuchElementException("Unknown property: " + propertyName);
  }
}
 
Example #5
Source Project: Strata   Author: OpenGamma   File: EtdContractSpec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object get(String propertyName) {
  switch (propertyName.hashCode()) {
    case 3355:  // id
      return id;
    case 3575610:  // type
      return type;
    case 913218206:  // exchangeId
      return exchangeId;
    case -1402840545:  // contractCode
      return contractCode;
    case -1724546052:  // description
      return description;
    case -2126070377:  // priceInfo
      return priceInfo;
    case 405645655:  // attributes
      return attributes;
    default:
      throw new NoSuchElementException("Unknown property: " + propertyName);
  }
}
 
Example #6
Source Project: nextcloud-notes   Author: stefan-niedermann   File: LocalAccount.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param availableApiVersions <code>["0.2", "1.0", ...]</code>
 */
public void setPreferredApiVersion(@Nullable String availableApiVersions) {
    // TODO move this logic to NotesClient?
    try {
        if (availableApiVersions == null) {
            this.preferredApiVersion = null;
            return;
        }
        JSONArray versionsArray = new JSONArray(availableApiVersions);
        Collection<ApiVersion> supportedApiVersions = new HashSet<>(versionsArray.length());
        for (int i = 0; i < versionsArray.length(); i++) {
            ApiVersion parsedApiVersion = ApiVersion.of(versionsArray.getString(i));
            for (ApiVersion temp : NotesClient.SUPPORTED_API_VERSIONS) {
                if (temp.compareTo(parsedApiVersion) == 0) {
                    supportedApiVersions.add(parsedApiVersion);
                    break;
                }
            }
        }
        this.preferredApiVersion = Collections.max(supportedApiVersions);
    } catch (JSONException | NoSuchElementException e) {
        e.printStackTrace();
        this.preferredApiVersion = null;
    }
}
 
Example #7
Source Project: SJS   Author: Samsung   File: GreedyFixingSetFinder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public FixingSetListener.Action currentFixingSet(Collection<T> out, FixingSetListener<T, ?> listener) {

    Collection<Collection<T>> cores = new LinkedList<>(this.cores);
    while (!cores.isEmpty()) {
        // At each iteration, pick the constraint that appears in the
        // greatest number of uncovered cores.

        Map<T, Integer> counts = cores.stream()
            .flatMap(Collection::stream)
            .collect(Collectors.toMap(
                c -> c,
                c -> 1,
                (v1, v2) -> v1 + v2));

        T constraint = allConstraints.stream()
            .filter(counts::containsKey)
            .max((c1, c2) -> counts.get(c1) - counts.get(c2))
            .orElseThrow(NoSuchElementException::new);
        out.add(constraint);
        cores.removeIf(core -> core.contains(constraint));
    }

    return FixingSetListener.Action.CONTINUE;
}
 
Example #8
Source Project: java-binary-block-parser   Author: raydac   File: JBBPTokenizerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testStructure_NonamedArray_Spaces() {
  final JBBPTokenizer parser = new JBBPTokenizer("    [ 333 ]  { ");

  final Iterator<JBBPToken> iterator = parser.iterator();

  final JBBPToken item = iterator.next();

  assertEquals(JBBPTokenType.STRUCT_START, item.getType());
  assertNull(item.getFieldName());
  assertNull(item.getFieldTypeParameters());
  assertTrue(item.isArray());
  assertEquals(333, item.getArraySizeAsInt().intValue());
  assertEquals(4, item.getPosition());

  try {
    iterator.next();
    fail("Must throw NSEE");
  } catch (NoSuchElementException ex) {

  }
}
 
Example #9
Source Project: monsoon   Author: groupon   File: ForwardIterator.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Advance along the chain.
 * @return The next chain element, or null if no more elements are available.
 */
public synchronized Chain<T> advance() {
    if (next_ == null) {
        if (!forward_.hasNext()) throw new NoSuchElementException();
        next_ = new Chain<>(forward_.next(), forward_);
        forward_ = null;
    }
    return next_;
}
 
Example #10
Source Project: dhis2-core   Author: dhis2   File: DefaultFileResourceService.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@Transactional( readOnly = true )
public void copyFileResourceContent( FileResource fileResource, OutputStream outputStream )
    throws IOException, NoSuchElementException
{
    fileResourceContentStore.copyContent( fileResource.getStorageKey(), outputStream );
}
 
Example #11
Source Project: pippo   Author: pippo-java   File: Stack.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Removes the top item from the stack and returns it.
 * Returns {@code null} if the stack is empty.
 */
public E pop() {
    try {
        return list.removeFirst();
    } catch (NoSuchElementException e) {
        return null;
    }
}
 
Example #12
Source Project: armeria   Author: line   File: HttpClientContextCaptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void badPath() {
    try (ClientRequestContextCaptor ctxCaptor = Clients.newContextCaptor()) {
        // Send a request with a bad path.
        // Note: A colon cannot come in the first path component.
        final HttpResponse res = WebClient.of().get("http://127.0.0.1:1/:");
        assertThatThrownBy(ctxCaptor::get).isInstanceOf(NoSuchElementException.class)
                                          .hasMessageContaining("no request was made");
        res.aggregate();
    }
}
 
Example #13
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: InsnList.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Object next() {
    if (next == null) {
        throw new NoSuchElementException();
    }
    AbstractInsnNode result = next;
    prev = result;
    next = result.next;
    remove = result;
    return result;
}
 
Example #14
Source Project: CloverETL-Engine   Author: CloverETL   File: StreamedPortDataBase.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public DataRecord peek() {
	if (current != null) {
		return current;
	}
	throw new NoSuchElementException();
}
 
Example #15
Source Project: Lightweight-Stream-API   Author: aNNiMON   File: OptionalIntTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = NoSuchElementException.class)
public void testOrElseThrow2() {
    assertEquals(25, OptionalInt.empty().orElseThrow(new Supplier<NoSuchElementException>() {
        @Override
        public NoSuchElementException get() {
            return new NoSuchElementException();
        }
    }));
}
 
Example #16
Source Project: fenixedu-academic   Author: FenixEdu   File: PhdMigrationGuiding.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public void parse() {
    try {
        String[] compounds = getData().split("\\t");

        this.phdStudentNumber = Integer.parseInt(compounds[0].trim());
        this.teacherId = compounds[2].trim();
        this.institutionCode = compounds[3].trim();
        this.name = compounds[4].trim();
    } catch (NoSuchElementException e) {
        throw new IncompleteFieldsException();
    }
}
 
Example #17
Source Project: jdk8u60   Author: chenghanpeng   File: SunFontManager.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void registerFontsOnPath(String pathName,
                                 boolean useJavaRasterizer, int fontRank,
                                 boolean defer, boolean resolveSymLinks) {

    StringTokenizer parser = new StringTokenizer(pathName,
            File.pathSeparator);
    try {
        while (parser.hasMoreTokens()) {
            registerFontsInDir(parser.nextToken(),
                    useJavaRasterizer, fontRank,
                    defer, resolveSymLinks);
        }
    } catch (NoSuchElementException e) {
    }
}
 
Example #18
Source Project: PowerSwitch_Android   Author: Power-Switch   File: Room.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets a specific Receiver in this Room, ignoring case
 *
 * @param name Name of Receiver
 * @return Receiver
 * @throws NoSuchElementException if no element was not found
 */
@NonNull
public Receiver getReceiverCaseInsensitive(@Nullable String name) {
    for (Receiver receiver : receivers) {
        if (receiver.getName().equalsIgnoreCase(name)) {
            return receiver;
        }
    }
    throw new NoSuchElementException("Receiver \"" + name + "\" not found");
}
 
Example #19
Source Project: j2cache   Author: mini188   File: DefaultCache.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<V> iterator() {
    return new Iterator<V>() {
        private final Iterator<DefaultCache.CacheWapper<V>> it = cachedObjects.iterator();

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

        @Override
        public V next() {
            if(it.hasNext()) {
                DefaultCache.CacheWapper<V> object = it.next();
                if(object == null) {
                    return null;
                } else {
                    return object.object;
                }
            }
            else {
                throw new NoSuchElementException();
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}
 
Example #20
Source Project: netbeans   Author: apache   File: NewWebProjectWizardIterator.java    License: Apache License 2.0 5 votes vote down vote up
public void nextPanel() {
    // To be able to trace #240974 a bit better, adding actual values
    if (!hasNext()) {
        StringBuilder sb = new StringBuilder();
        sb.append("panelsCount: ");
        sb.append(panelsCount);
        sb.append("\n panels size: ");
        sb.append(panels.length);
        throw new NoSuchElementException(sb.toString());
    }
    index++;
}
 
Example #21
Source Project: astor   Author: SpoonLabs   File: StrTokenizer.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the next token.
 *
 * @return the next String token
 * @throws NoSuchElementException if there are no more elements
 */
@Override
public String next() {
    if (hasNext()) {
        return tokens[tokenPos++];
    }
    throw new NoSuchElementException();
}
 
Example #22
Source Project: java-katas   Author: c-guntur   File: TestKata2OptionalConditionalFetching.java    License: MIT License 5 votes vote down vote up
@Test
@DisplayName("return a value either from non-empty Optional or throw Exception")
@Tag("TODO")
@Order(4)
public void orElseThrowReplacesOptionalGet() {

    /*
     * NOTE: Refer to the bug: https://bugs.openjdk.java.net/browse/JDK-8140281
     *
     * This is a deliberate API addition to "replace" or "deprecate" the get()
     * get() brings about an ambiguity, when used without an ifPresent().
     *
     * Bug for get() deprecation: https://bugs.openjdk.java.net/browse/JDK-8160606
     */

    Optional<String> anOptional = Optional.empty();

    /*
     * TODO:
     *  Replace the below to use an orElseThrow() - instead of - the get()
     *  Check API: java.util.Optional.orElseThrow()
     */
    assertThrows(NoSuchElementException.class, () -> {
        String nonNullString = null;
    });

}
 
Example #23
Source Project: ezdb   Author: criccomini   File: TestEzBytesTreeMapDb.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void range2ReverseMinus() {
	final TableIterator<String, Date, Integer> range = reverseRangeTable.rangeReverse(HASHKEY_ONE, twoDateMinus);
	Assert.assertEquals(1, (int) range.next().getValue());
	Assert.assertFalse(range.hasNext());
	try {
		range.next();
		Assert.fail("Exception expected!");
	} catch (final NoSuchElementException e) {
		Assert.assertNotNull(e);
	}
}
 
Example #24
Source Project: grappa   Author: fge   File: ArrayValueStack.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public T next()
{
    if (!hasNext())
        throw new NoSuchElementException();
    return array[index++];
}
 
Example #25
Source Project: gemfirexd-oss   Author: gemxd   File: OptionSpecTokenizer.java    License: Apache License 2.0 5 votes vote down vote up
AbstractOptionSpec<?> next() {
    if ( !hasMore() )
        throw new NoSuchElementException();


    String optionCandidate = String.valueOf( specification.charAt( index ) );
    index++;

    AbstractOptionSpec<?> spec;
    if ( RESERVED_FOR_EXTENSIONS.equals( optionCandidate ) ) {
        spec = handleReservedForExtensionsToken();

        if ( spec != null )
            return spec;
    }

    ensureLegalOption( optionCandidate );

    if ( hasMore() ) {
        boolean forHelp = false;
        if ( specification.charAt( index ) == HELP_MARKER ) {
            forHelp = true;
            ++index;
        }
        spec = hasMore() && specification.charAt( index ) == ':'
            ? handleArgumentAcceptingOption( optionCandidate )
            : new NoArgumentOptionSpec( optionCandidate );
        if ( forHelp )
            spec.forHelp();
    } else
        spec = new NoArgumentOptionSpec( optionCandidate );

    return spec;
}
 
Example #26
Source Project: ezdb   Author: criccomini   File: TestEzLmDbJni.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Test
public void range32ReversePlus() {
	final TableIterator<String, Date, Integer> range = reverseRangeTable.rangeReverse(HASHKEY_ONE, threeDatePlus,
			twoDatePlus);
	Assert.assertEquals(3, (int) range.next().getValue());
	Assert.assertFalse(range.hasNext());
	try {
		range.next();
		Assert.fail("Exception expected!");
	} catch (final NoSuchElementException e) {
		Assert.assertNotNull(e);
	}
}
 
Example #27
Source Project: SourcererCC   Author: Mondego   File: CloneReporter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    try {
        this.reportClone(this.cp);
    } catch (NoSuchElementException e) {
        e.printStackTrace();
    }
}
 
Example #28
Source Project: org.alloytools.alloy   Author: AlloyTools   File: IntBitSet.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int next() {
    if (!hasNext())
        throw new NoSuchElementException();
    final long lastReturnedMask = Long.highestOneBit(unseen);
    unseen -= lastReturnedMask;
    lastReturned = (unseenIndex << 6) + 63 - Long.numberOfLeadingZeros(lastReturnedMask);
    return lastReturned;
}
 
Example #29
Source Project: components   Author: Talend   File: AzureStorageQueueInputReaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = NoSuchElementException.class)
public void testGetCurrentWhenNotAdvancable() {
    try {
        properties.peekMessages.setValue(true);

        AzureStorageQueueSource source = new AzureStorageQueueSource();
        ValidationResult vr = source.initialize(getDummyRuntimeContiner(), properties);
        assertNotNull(vr);
        assertEquals(ValidationResult.OK.getStatus(), vr.getStatus());

        reader = (AzureStorageQueueInputReader) source.createReader(getDummyRuntimeContiner());
        reader.queueService = queueService; // inject mocked service

        final List<CloudQueueMessage> messages = new ArrayList<>();
        messages.add(new CloudQueueMessage("message-1"));
        when(queueService.peekMessages(anyString(), anyInt())).thenReturn(new Iterable<CloudQueueMessage>() {

            @Override
            public Iterator<CloudQueueMessage> iterator() {
                return new DummyCloudQueueMessageIterator(messages);
            }
        });
        boolean startable = reader.start();
        assertTrue(startable);
        assertNotNull(reader.getCurrent());
        boolean advancable = reader.advance();
        assertFalse(advancable);
        reader.getCurrent(); // should throw NoSuchElementException

    } catch (IOException | InvalidKeyException | URISyntaxException | StorageException e) {
        fail("sould not throw " + e.getMessage());
    }
}
 
Example #30
Source Project: kafka-workers   Author: RTBHOUSE   File: RandomAccessArrayDeque.java    License: Apache License 2.0 5 votes vote down vote up
public final E next() {
    if (remaining <= 0)
        throw new NoSuchElementException();
    final Object[] es = elements;
    E e = nonNullElementAt(es, cursor);
    cursor = dec(lastRet = cursor, es.length);
    remaining--;
    return e;
}