Example usage for java.util NoSuchElementException NoSuchElementException

List of usage examples for java.util NoSuchElementException NoSuchElementException

Introduction

In this page you can find the example usage for java.util NoSuchElementException NoSuchElementException.

Prototype

public NoSuchElementException(String s) 

Source Link

Document

Constructs a NoSuchElementException , saving a reference to the error message string s for later retrieval by the getMessage method.

Usage

From source file:de.micromata.genome.tpsb.htmlunit.By.java

/**
 * Find a single element. Override this method if necessary.
 * /*ww  w .  j a v  a  2  s  .  c om*/
 * @param context A context to use to find the element
 * @return The WebElement that matches the selector
 */
public Element findElement(HtmlPage context) {
    List<Element> allElements = findElements(context);
    if (allElements == null || allElements.size() == 0)
        throw new NoSuchElementException("Cannot locate an element using " + toString());
    return allElements.get(0);
}

From source file:com.ebay.erl.mobius.core.collection.BigTupleListIterator.java

@Override
public Tuple next() {
    if (this.hasNext()) {
        this.checkConcurrentModification();

        // pop the first one
        TupleToBuffer elem = this.sortingBuffer.removeFirst();

        // get the corresponding source
        this.tupleSources.get(elem.belongedQueueIdx).remove();
        this.currentReadTuples++;

        if (this.currentReadTuples % 1000 == 0 && this.bigList.reporter != null) {
            this.bigList.reporter.setStatus("Iterated " + this.currentReadTuples + " tuples.");
        }/*w  w  w  .j  a v  a  2 s . c o  m*/

        return elem.tuple;
    } else {
        throw new NoSuchElementException("No more element available.");
    }
}

From source file:FSM.java

/**
 * Establish a new transition. You might use this method something like
 * this:/*w  ww. j  a  v  a  2  s.  c om*/
 * 
 * fsm.addTransition(new FSM.Transition("someEvent", "firstState",
 * "secondState") { public void doBeforeTransition() {
 * System.out.println("about to transition..."); } public void
 * doAfterTransition() { fancyOperation(); } });
 */
public void addTransition(Transition trans) {
    State st = states.get(trans.startState);
    if (st == null) {
        throw new NoSuchElementException("Missing state: " + trans.startState);
    }
    st.addTransition(trans);
}

From source file:de.tudarmstadt.ukp.dkpro.argumentation.io.annotations.SpanAnnotationGraph.java

public Map<String, T> getLabels(final Span span) {
    Map<String, T> result;
    final Int2ObjectMap<? extends Int2ObjectMap<? extends Map<String, T>>> annotMatrix = getSpanAnnotationMatrix();
    final int begin = span.getBegin();
    final Int2ObjectMap<? extends Map<String, T>> firstDim = annotMatrix.get(begin);
    if (firstDim == annotMatrix.defaultReturnValue()) {
        throw new NoSuchElementException(String.format("Span begin index %d not found in matrix.", begin));
    }// w w  w .j  a v a 2s . c om
    final int end = span.getEnd();
    result = firstDim.get(end);
    if (result == firstDim.defaultReturnValue()) {
        throw new NoSuchElementException(String.format("Span end index %d not found in matrix.", end));
    }
    return result;

}

From source file:AccessibleFieldIterator.java

public T next() {
    if (iteratorQueue.size() == 0) {
        throw new NoSuchElementException("no more elements");
    }//from  w  w w  .  jav  a  2s  .  c  o m
    last = iteratorQueue.poll();
    nextCalled = true;
    return last;
}

From source file:com.devicehive.service.UserService.java

@Transactional(propagation = Propagation.REQUIRED)
public UserVO updateUser(@NotNull Long id, UserUpdate userToUpdate, UserRole role) {
    UserVO existing = userDao.find(id);/*from ww  w.  j av a  2 s .  co  m*/

    if (existing == null) {
        logger.error("Can't update user with id {}: user not found", id);
        throw new NoSuchElementException(Messages.USER_NOT_FOUND);
    }
    if (userToUpdate == null) {
        return existing;
    }
    if (userToUpdate.getLogin() != null) {
        final String newLogin = StringUtils.trim(userToUpdate.getLogin().orElse(null));
        final String oldLogin = existing.getLogin();
        Optional<UserVO> withSuchLogin = userDao.findByName(newLogin);

        if (withSuchLogin.isPresent() && !withSuchLogin.get().getId().equals(id)) {
            throw new ActionNotAllowedException(Messages.DUPLICATE_LOGIN);
        }
        existing.setLogin(newLogin);

        final String googleLogin = StringUtils.isNotBlank(userToUpdate.getGoogleLogin().orElse(null))
                ? userToUpdate.getGoogleLogin().orElse(null)
                : null;
        final String facebookLogin = StringUtils.isNotBlank(userToUpdate.getFacebookLogin().orElse(null))
                ? userToUpdate.getFacebookLogin().orElse(null)
                : null;
        final String githubLogin = StringUtils.isNotBlank(userToUpdate.getGithubLogin().orElse(null))
                ? userToUpdate.getGithubLogin().orElse(null)
                : null;

        if (googleLogin != null || facebookLogin != null || githubLogin != null) {
            Optional<UserVO> userWithSameIdentity = userDao.findByIdentityName(oldLogin, googleLogin,
                    facebookLogin, githubLogin);
            if (userWithSameIdentity.isPresent()) {
                throw new ActionNotAllowedException(Messages.DUPLICATE_IDENTITY_LOGIN);
            }
        }
        existing.setGoogleLogin(googleLogin);
        existing.setFacebookLogin(facebookLogin);
        existing.setGithubLogin(githubLogin);
    }
    if (userToUpdate.getPassword() != null) {
        if (userToUpdate.getOldPassword() != null
                && StringUtils.isNotBlank(userToUpdate.getOldPassword().orElse(null))) {
            final String hash = passwordService.hashPassword(userToUpdate.getOldPassword().orElse(null),
                    existing.getPasswordSalt());
            if (!hash.equals(existing.getPasswordHash())) {
                logger.error("Can't update user with id {}: incorrect password provided", id);
                throw new ActionNotAllowedException(Messages.INCORRECT_CREDENTIALS);
            }
        } else if (role == UserRole.CLIENT) {
            logger.error("Can't update user with id {}: old password required", id);
            throw new ActionNotAllowedException(Messages.OLD_PASSWORD_REQUIRED);
        }
        if (StringUtils.isEmpty(userToUpdate.getPassword().orElse(null))) {
            logger.error("Can't update user with id {}: password required", id);
            throw new IllegalParametersException(Messages.PASSWORD_REQUIRED);
        }
        String salt = passwordService.generateSalt();
        String hash = passwordService.hashPassword(userToUpdate.getPassword().orElse(null), salt);
        existing.setPasswordSalt(salt);
        existing.setPasswordHash(hash);
    }
    if (userToUpdate.getStatus() != null || userToUpdate.getRole() != null) {
        if (role != UserRole.ADMIN) {
            logger.error(
                    "Can't update user with id {}: users eith the 'client' role are only allowed to change their password",
                    id);
            throw new HiveException(Messages.INVALID_USER_ROLE, FORBIDDEN.getStatusCode());
        } else if (userToUpdate.getRoleEnum() != null) {
            existing.setRole(userToUpdate.getRoleEnum());
        } else {
            existing.setStatus(userToUpdate.getStatusEnum());
        }
    }
    if (userToUpdate.getData() != null) {
        existing.setData(userToUpdate.getData().orElse(null));
    }
    hiveValidator.validate(existing);
    return userDao.merge(existing);
}

From source file:com.asakusafw.runtime.io.text.csv.CsvFieldReader.java

@Override
public CharSequence getContent() {
    switch (lastState) {
    case END_OF_FIELD:
    case END_OF_RECORD:
        return fieldBuffer;
    case BEFORE_RECORD:
    case AFTER_RECORD:
        throw new NoSuchElementException(
                String.format("line-number=%,d, record-index=%,d, field-index=%,d, last-state=%s", //$NON-NLS-1$
                        getRecordLineNumber(), getRecordIndex(), getFieldIndex(), lastState));
    default://from www .  j a  v  a  2s. co m
        throw new AssertionError(lastState);
    }
}

From source file:fr.cls.atoll.motu.library.misc.utils.PropertiesUtilities.java

/**
 * Replace in the properties values the name of the system variable that follows the scheme
 * <tt>${var}<tt> with their corresponding values.
 * /* w  w  w  .  j  a  v a2  s.c o m*/
 * @param props properties to substitute.
 */
static public void replaceSystemVariable(Properties props) {
    Iterator it;
    Map.Entry entry;
    String value;
    for (it = props.entrySet().iterator(); it.hasNext();) {
        entry = (Map.Entry) it.next();
        try {
            value = replaceSystemVariable((String) entry.getValue());
        } catch (NoSuchElementException ex) {
            throw new NoSuchElementException(
                    ex.getMessage() + " subsitution for property " + (String) entry.getKey());
        }
        entry.setValue(value);
    }
}

From source file:org.zenoss.app.consumer.metric.impl.OpenTsdbWriter.java

void processBatch(Collection<Metric> metrics) throws InterruptedException {
    OpenTsdbClient client = null;//ww  w  .ja  v a  2  s.  co m
    boolean flushed = false;
    boolean invalidateClient = false;
    long processed = 0;
    try {
        client = getOpenTsdbClient();
        if (client != null) {
            int errs = clientPool.clearErrorCount();
            if (errs > 0) {
                metricsQueue.incrementError(errs);
            }

            if (clientPool.hasCollision()) {
                // Note: calling .hasCollision() also had the side-effect of clearing it.
                invalidateClient = true;
                eventBus.post(Control.highCollision());
                throw new NoSuchElementException("Collision detected");
            }

            try {
                for (Metric m : metrics) {
                    // ZEN-11665 - make copy of metric before messing with it. This prevents side-effect issues when exceptions occur.
                    Metric workingCopy = new Metric(m);
                    workingCopy.removeTag(TsdbMetricsQueue.CLIENT_TAG);
                    String message = null;
                    try {
                        message = convert(workingCopy);
                    } catch (RuntimeException e) {
                        if (log.isDebugEnabled()) {
                            log.warn(String.format("Dropping bad metric : %s : %s", e.getMessage(),
                                    workingCopy.toString()), e);
                        } else {
                            log.warn("Dropping bad metric : {} : {}", e.getMessage(), workingCopy);
                        }
                        processed++;
                    }
                    if (message != null) {
                        try {
                            client.put(message);
                            processed++;
                        } catch (IOException e) {
                            log.warn("Caught (and rethrowing) IOException while processing metric: {}",
                                    e.getMessage());
                            throw e;
                        }
                    }
                }
                boolean anyErrors = false;
                for (String error : client.checkForErrors()) {
                    log.warn("OpenTSDB returned an error: {}", error);
                    anyErrors = true;
                }
                if (anyErrors) {
                    invalidateClient = true;
                } else {
                    flushed = true;
                }
            } catch (IOException e) {
                log.warn("Caught exception while processing messages: {}", e.getMessage());
                invalidateClient = true;
            }
        } else {
            log.warn("Unable to get client to process metrics.");
        }
    } finally {
        if (flushed) {
            metricsQueue.incrementProcessed(processed);
        } else {
            try {
                metricsQueue.reAddAll(metrics);
            } catch (Exception e) {
                log.error(
                        "We were unable to add metrics back to the queue. Eating exception to prevent thread death.",
                        e);
                metricsQueue.incrementLostMetrics(metrics.size());
            }
        }
        if (client != null) {
            try {
                if (invalidateClient)
                    clientPool.invalidateObject(client);
                else
                    clientPool.returnObject(client);
            } catch (Exception releaseException) {
                log.warn("Error while releasing TSDB client", releaseException);
            }
        }
        lastWorkTime = System.currentTimeMillis();
    }
}

From source file:de.tudarmstadt.ukp.dkpro.argumentation.io.annotations.SpanAnnotationGraph.java

public T getRelationTarget(final T source) throws NoSuchElementException {
    final T result;

    final int sourceId = getId(source);
    if (sourceId < 0) {
        throw new NoSuchElementException("Not found in relation table: " + source);
    }/*  w  w w. ja  v  a2 s.  co m*/
    final int targetId = relationTransitionTable[sourceId];
    result = targetId < 0 ? null : get(targetId);

    return result;
}