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:com.buaa.cfs.fs.AbstractFileSystem.java

/**
 * The specification of this method matches that of {@link FileContext#listLocatedStatus(Path)} except that Path f
 * must be for this file system./*w w w  .jav  a 2s .co  m*/
 */
public RemoteIterator<LocatedFileStatus> listLocatedStatus(final Path f)
        throws AccessControlException, FileNotFoundException, UnresolvedLinkException, IOException {
    return new RemoteIterator<LocatedFileStatus>() {
        private RemoteIterator<FileStatus> itor = listStatusIterator(f);

        @Override
        public boolean hasNext() throws IOException {
            return itor.hasNext();
        }

        @Override
        public LocatedFileStatus next() throws IOException {
            if (!hasNext()) {
                throw new NoSuchElementException("No more entry in " + f);
            }
            FileStatus result = itor.next();
            BlockLocation[] locs = null;
            if (result.isFile()) {
                locs = getFileBlockLocations(result.getPath(), 0, result.getLen());
            }
            return new LocatedFileStatus(result, locs);
        }
    };
}

From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java

/**
 * Extracts from a {@link JSONObject} the value of the field referenced by the provided path. The result may contain
 * any valid structure type contained inside the {@link JSONObject}, eg. {@link JSONObject} itself, {@link JSONArray} instances
 * or plain java types ({@link Integer}, {@link String}, ...) 
 * @param jsonObject/*from www.jav  a 2s .co m*/
 *          The {@link JSONObject} to read the value from (null is not permitted as input)
 * @param fieldPath
 *          Path inside the {@link JSONObject} pointing towards the value of interest (null is not permitted as input)
 * @return
 *          Value found at the end of the provided path. An empty path simply returns the input
 * @throws JSONException
 *          Thrown in case extracting values from the {@link JSONObject} fails for any reason
 * @throws IllegalArgumentException
 *          Thrown in case a provided parameter does not comply with the restrictions
 * @throws NoSuchElementException
 *          Thrown in case an element referenced inside the path does not exist at the expected location inside the {@link JSONObject} 
 */
public Object getFieldValue(final JSONObject jsonObject, final String[] fieldPath, final boolean required)
        throws JSONException, IllegalArgumentException, NoSuchElementException {
    /////////////////////////////////////////////////////////////////////////
    // validate provided input and throw exceptions if required
    if (jsonObject == null)
        throw new IllegalArgumentException("Null is not permitted as input to json object parameter");
    if (fieldPath == null)
        throw new IllegalArgumentException("Null is not permitted as input to field path parameter");
    if (fieldPath.length < 1)
        return jsonObject;
    /////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////
    // if the field path has only one element left, check if it points towards an array value which is read out if available 
    // or if it simply points to a plain element inside the json which is returned otherwise
    if (fieldPath.length == 1) {

        // check if the field path references an array and return its value if possible 
        if (containsArrayReference(fieldPath[0]))
            return getArrayElement(jsonObject, fieldPath[0]);

        // otherwise check if the field points to an existing "plain" element and return 
        // its value ... or throw an exception
        if (!jsonObject.has(fieldPath[0])) {
            if (!required)
                return null;
            throw new NoSuchElementException(
                    "Path element '" + fieldPath[0] + "' does not exist for provided JSON object");
        }
        return jsonObject.get(fieldPath[0]);
    }
    /////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////
    // check if the next field path contains an array reference
    if (containsArrayReference(fieldPath[0])) {
        Object value = getArrayElement(jsonObject, fieldPath[0]);
        // if the value is not an JSONObject throw an exception
        if (value instanceof JSONObject)
            return getFieldValue((JSONObject) value, Arrays.copyOfRange(fieldPath, 1, fieldPath.length),
                    required);

        if (!required)
            return null;

        throw new NoSuchElementException(
                "Referenced array element '" + fieldPath[0] + "' does not point to a valid JSON object");
    }
    /////////////////////////////////////////////////////////////////////////

    if (!jsonObject.has(fieldPath[0])) {
        if (!required)
            return null;
        throw new NoSuchElementException(
                "Path element '" + fieldPath[0] + "' does not exist for provided JSON object");
    }
    Object value = jsonObject.get(fieldPath[0]);
    if (value instanceof JSONObject)
        return getFieldValue((JSONObject) value, Arrays.copyOfRange(fieldPath, 1, fieldPath.length), required);

    if (!required)
        return null;

    throw new NoSuchElementException("Referenced element '" + fieldPath[0] + "' is not a valid JSON object");
}

From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java

/**
 * Attempts to read the value from the path element which expectedly points to an array (nested arrays are supported)
 * @param json/* ww w . j  a v a 2s  .co  m*/
 *          {@link JSONObject} instance which is expected to hold a {@link JSONArray} at the provided path element
 * @param pathElement
 *          Path element pointing to a {@link JSONArray} structure inside the provided {@link JSONObject} instance. Example: <code>value[1] or value[1][2]</code> 
 * @return
 *          Value inside the referenced {@link JSONArray} element
 * @throws JSONException
 * @throws NoSuchElementException
 */
protected Object getArrayElement(final JSONObject json, final String pathElement)
        throws JSONException, NoSuchElementException {

    /////////////////////////////////////////////////////////////////////////
    // validate provided input and throw exceptions if required
    if (json == null)
        throw new IllegalArgumentException("Null is not permitted as input to json object parameter");
    if (pathElement == null)
        throw new IllegalArgumentException("Null is not permitted as input to path parameter");
    if (StringUtils.isBlank(pathElement))
        return json;
    /////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////
    // extract and access referenced field to ensure that it holds an array
    String field = pathElement.substring(0, pathElement.indexOf('['));
    if (!json.has(field))
        throw new NoSuchElementException(
                "Path element '" + field + "' does not exist for provided JSON object");
    Object fieldContent = json.get(field);
    if (!(fieldContent instanceof JSONArray))
        throw new NoSuchElementException("Referenced element '" + field + "' is not an array");
    /////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////
    // extract referenced positions - nested arrays supported
    String[] tempSplits = pathElement.substring(pathElement.indexOf('[') + 1).split("\\]\\[");
    int[] positions = new int[tempSplits.length];

    // iterate through splits and extract positions -- remove trailing brackets which may
    // remain there as result of splitting
    for (int i = 0; i < tempSplits.length; i++) {
        String split = tempSplits[i];
        if (StringUtils.endsWith(split, "]"))
            split = split.substring(0, split.length() - 1);
        positions[i] = Integer.valueOf(split);
    }
    /////////////////////////////////////////////////////////////////////////

    /////////////////////////////////////////////////////////////////////////
    // step through array positions and attempt to extract value
    Object posValue = fieldContent;
    for (int i = 0; i < positions.length; i++) {
        posValue = getArrayElement((JSONArray) posValue, positions[i]);
        if (i < positions.length - 1) {
            if (!(posValue instanceof JSONArray))
                throw new NoSuchElementException(
                        "Referenced array element does not hold a nested array as expected");
        }
    }
    /////////////////////////////////////////////////////////////////////////

    return posValue;

}

From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java

/**
 * Returns the value from the provided array referenced by the given position 
 * @param array//from  w  w  w .j  av  a2 s.  c o m
 *          The {@link JSONArray} to read the value from
 * @param position
 *          The position to read the value from. Starts with first position at zero
 * @return
 *          The value located at the given position inside the {@link JSONArray}
 * @throws JSONException
 *          Thrown in case accessing the {@link JSONArray} fails for any reason
 * @throws NoSuchElementException
 *          Thrown in case the value of the position parameter points to a non-existing element 
 * @throws IllegalArgumentException
 *          Thrown in case the {@link JSONArray} is not a valid instance
 */
protected Object getArrayElement(final JSONArray array, final int position)
        throws JSONException, NoSuchElementException, IllegalArgumentException {
    if (array == null)
        throw new IllegalArgumentException("Null is not permitted as input to array parameter");
    if (position < 0 || position > array.length() - 1)
        throw new NoSuchElementException(
                "Referenced position '" + position + "' does not exist in provided array");
    return array.get(position);
}

From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java

/**
 * Updates the element at the referenced position inside the array using the given value 
 * @param array/*from   w  ww. j  ava2  s  . c  o  m*/
 *          The {@link JSONArray} to update
 * @param position
 *          The position to update. Starts with first position at zero
 * @param value
 *          The value to insert at the given location
 * @throws JSONException
 *          Thrown in case accessing the {@link JSONArray} fails for any reason
 * @throws NoSuchElementException
 *          Thrown in case the value of the position parameter points to a non-existing element 
 * @throws IllegalArgumentException
 *          Thrown in case the {@link JSONArray} is not a valid instance
 */
protected void updateArrayElement(final JSONArray array, final int position, final Serializable value)
        throws JSONException, NoSuchElementException, IllegalArgumentException {
    if (array == null)
        throw new IllegalArgumentException("Null is not permitted as input to array parameter");
    if (position < 0 || position > array.length() - 1)
        throw new NoSuchElementException(
                "Referenced position '" + position + "' does not exist in provided array");
    array.put(position, value);
}

From source file:de.mrapp.android.adapter.expandablelist.AbstractExpandableListAdapter.java

/**
 * Returns the index of a specific group item or throws a {@link NoSuchElementException} if the
 * adapter does not contain the group item.
 *
 * @param group//from   w w  w .  j  a v a  2s . c  om
 *         The group item, whose index should be returned, as an instance of the generic type
 *         GroupType. The group item may not be null
 * @return The index of the the given group item, as an {@link Integer} value
 */
protected final int indexOfGroupOrThrowException(@NonNull final GroupType group) {
    int groupIndex = indexOfGroup(group);

    if (groupIndex != -1) {
        return groupIndex;
    } else {
        throw new NoSuchElementException("Adapter does not contain group \"" + group + "\"");
    }
}

From source file:de.mrapp.android.adapter.expandablelist.AbstractExpandableListAdapter.java

/**
 * Returns the index of a specific child item within the group, which belongs to a specific
 * index, or throws a {@link NoSuchElementException} if the group does not contain the child
 * item.//from   w  w  w.  j a  v  a  2s.com
 *
 * @param groupIndex
 *         The index of the group, the child item, whose index should be returned, belongs to,
 *         as an {@link Integer} value. The value must be between 0 and the value of the method
 *         <code>getGroupCount():int</code> - 1, otherwise an {@link IndexOutOfBoundsException}
 *         will be thrown
 * @param child
 *         The child item, whose index should be returned, as an instance of the generic type
 *         ChildType. The child item may not be null
 * @return The index of the given child item, as an {@link Integer} value
 */
protected final int indexOfChildOrThrowException(final int groupIndex, @NonNull final ChildType child) {
    int childIndex = indexOfChild(groupIndex, child);

    if (childIndex != -1) {
        return childIndex;
    } else {
        throw new NoSuchElementException("Group \"" + getGroup(groupIndex) + "\" at index " + groupIndex
                + " does not contain child \"" + child + "\"");
    }
}

From source file:com.meidusa.amoeba.net.poolable.copy.GenericObjectPool.java

public Object borrowObject() throws Exception {
    long starttime = System.currentTimeMillis();
    for (;;) {/*  ww  w .j  a  v  a2s .c o m*/
        ObjectTimestampPair pair = null;

        lock.lock();
        try {
            assertOpen();
            // if there are any sleeping, just grab one of those
            try {
                pair = (ObjectTimestampPair) (_pool.removeFirst());
            } catch (NoSuchElementException e) {
                ; /* ignored */
            }
        } finally {
            lock.unlock();
        }
        // otherwise
        if (null == pair) {
            // check if we can create one
            // (note we know that the num sleeping is 0, else we wouldn't be here)
            if (_maxActive < 0 || _numActive < _maxActive) {
                // allow new object to be created
            } else {
                // the pool is exhausted
                switch (_whenExhaustedAction) {
                case WHEN_EXHAUSTED_GROW:
                    // allow new object to be created
                    break;
                case WHEN_EXHAUSTED_FAIL:
                    throw new NoSuchElementException("Pool exhausted");
                case WHEN_EXHAUSTED_BLOCK:
                    synchronized (this) {
                        try {
                            if (_maxWait <= 0) {
                                wait();
                            } else {
                                // this code may be executed again after a notify then continue cycle
                                // so, need to calculate the amount of time to wait
                                final long elapsed = (System.currentTimeMillis() - starttime);
                                final long waitTime = _maxWait - elapsed;
                                if (waitTime > 0) {
                                    wait(waitTime);
                                }
                            }
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            throw e;
                        }
                    }
                    if (_maxWait > 0 && ((System.currentTimeMillis() - starttime) >= _maxWait)) {
                        throw new NoSuchElementException("Timeout waiting for idle object");
                    } else {
                        continue; // keep looping
                    }
                default:
                    throw new IllegalArgumentException(
                            "WhenExhaustedAction property " + _whenExhaustedAction + " not recognized.");
                }
            }
        }

        // create new object when needed
        boolean newlyCreated = false;
        boolean numIncreased = false;
        if (null == pair) {
            if (_maxActive < 0 || this.getNumActive() < _maxActive
                    || _whenExhaustedAction != WHEN_EXHAUSTED_BLOCK) {
                lock.lock();
                try {
                    if (_numActive < _maxActive) {
                        _numActive++;
                        numIncreased = true;
                    } else {
                        continue;
                    }
                } finally {
                    lock.unlock();
                }
                try {
                    Object obj = _factory.makeObject();
                    pair = new ObjectTimestampPair(obj);
                    newlyCreated = true;
                } catch (Exception e) {
                    lock.lock();
                    try {
                        _numActive--;
                        numIncreased = false;
                    } finally {
                        lock.unlock();
                    }
                    throw e;
                }
            } else {
                continue;
            }
        }

        // activate & validate the object
        try {
            if (_testOnBorrow && !_factory.validateObject(pair.value)) {
                throw new Exception("ValidateObject failed");
            }
            _factory.activateObject(pair.value);
            if (!numIncreased) {
                lock.lock();
                try {
                    _numActive++;
                    numIncreased = true;
                } finally {
                    lock.unlock();
                }
            }
            return pair.value;
        } catch (Throwable e) {
            if (numIncreased) {
                lock.lock();
                try {
                    _numActive--;
                } finally {
                    lock.unlock();
                }
            }
            // object cannot be activated or is invalid
            try {
                _factory.destroyObject(pair.value);
            } catch (Throwable e2) {
                // cannot destroy broken object
            }
            if (newlyCreated) {
                throw new NoSuchElementException(
                        "Could not create a validated object, cause: " + e.getMessage());
            } else {
                continue; // keep looping
            }
        }
    }
}

From source file:com.buaa.cfs.fs.FileSystem.java

/**
 * Listing a directory The returned results include its block location if it is a file The results are filtered by
 * the given path filter//from w  w w  .j  a  v  a  2 s. co  m
 *
 * @param f      a path
 * @param filter a path filter
 *
 * @return an iterator that traverses statuses of the files/directories in the given path
 *
 * @throws FileNotFoundException if <code>f</code> does not exist
 * @throws IOException           if any I/O error occurred
 */
protected RemoteIterator<LocatedFileStatus> listLocatedStatus(final Path f, final PathFilter filter)
        throws FileNotFoundException, IOException {
    return new RemoteIterator<LocatedFileStatus>() {
        private final FileStatus[] stats = listStatus(f, filter);
        private int i = 0;

        @Override
        public boolean hasNext() {
            return i < stats.length;
        }

        @Override
        public LocatedFileStatus next() throws IOException {
            if (!hasNext()) {
                throw new NoSuchElementException("No more entry in " + f);
            }
            FileStatus result = stats[i++];
            BlockLocation[] locs = result.isFile() ? getFileBlockLocations(result.getPath(), 0, result.getLen())
                    : null;
            return new LocatedFileStatus(result, locs);
        }
    };
}

From source file:com.buaa.cfs.fs.FileSystem.java

/**
 * Returns a remote iterator so that followup calls are made on demand while consuming the entries. Each file system
 * implementation should override this method and provide a more efficient implementation, if possible.
 *
 * @param p target path//from  w  ww.  jav  a 2 s. com
 *
 * @return remote iterator
 */
public RemoteIterator<FileStatus> listStatusIterator(final Path p) throws FileNotFoundException, IOException {
    return new RemoteIterator<FileStatus>() {
        private final FileStatus[] stats = listStatus(p);
        private int i = 0;

        @Override
        public boolean hasNext() {
            return i < stats.length;
        }

        @Override
        public FileStatus next() throws IOException {
            if (!hasNext()) {
                throw new NoSuchElementException("No more entry in " + p);
            }
            return stats[i++];
        }
    };
}