Example usage for java.lang IndexOutOfBoundsException IndexOutOfBoundsException

List of usage examples for java.lang IndexOutOfBoundsException IndexOutOfBoundsException

Introduction

In this page you can find the example usage for java.lang IndexOutOfBoundsException IndexOutOfBoundsException.

Prototype

public IndexOutOfBoundsException(int index) 

Source Link

Document

Constructs a new IndexOutOfBoundsException class with an argument indicating the illegal index.

Usage

From source file:com.google.uzaygezen.core.LongArrayBitVector.java

private void checkRange(int low, int high, int... values) {
    for (int v : values) {
        if (v < low || v > high) {
            throw new IndexOutOfBoundsException("index " + v + " should be in [" + low + ".." + high + "]");
        }/*  w w w .  j a  va2  s  .  c o  m*/
    }
}

From source file:com.microsoft.azure.management.datalake.store.uploader.StringExtensions.java

/**
 * Finds the index in the given buffer of a newline character, either the first or the last (based on the parameters).
 * If a combined newline (\r\n), the index returned is that of the last character in the sequence.
 *
 * @param buffer The buffer to search in.
 * @param startOffset The index of the first byte to start searching at.
 * @param length The number of bytes to search, starting from the given startOffset.
 * @param reverse If true, searches from the startOffset down to the beginning of the buffer. If false, searches upwards.
 * @param encoding Indicates the type of encoding to use for the buffered bytes.
 * @param delimiter Optionally indicates the delimiter to consider as the "new line", which MUST BE a single character. If null, the default is '\\r', '\\n' and '\\r\\n'.
 * @return The index of the closest newline character in the sequence (based on direction) that was found. Returns -1 if not found.
 *//* w w w .  ja  va  2s.co  m*/
public static int findNewline(byte[] buffer, int startOffset, int length, boolean reverse, Charset encoding,
        String delimiter) {
    if (buffer.length == 0 || length == 0) {
        return -1;
    }

    // define the bytes per character to use
    int bytesPerChar;
    if (encoding.equals(StandardCharsets.UTF_16) || encoding.equals(StandardCharsets.UTF_16BE)
            || encoding.equals(StandardCharsets.UTF_16LE)) {
        bytesPerChar = 2;
    } else if (encoding.equals(StandardCharsets.US_ASCII) || encoding.equals(StandardCharsets.UTF_8)) {
        bytesPerChar = 1;
    } else {
        throw new IllegalArgumentException(
                "Only the following encodings are allowed: UTF-8, UTF-16, UTF-16BE, UTF16-LE and ASCII");
    }

    if (delimiter != null && !StringUtils.isEmpty(delimiter) && delimiter.length() > 1) {
        throw new IllegalArgumentException(
                "The delimiter must only be a single character or unspecified to represent the CRLF delimiter");
    }

    if (delimiter != null && !StringUtils.isEmpty(delimiter)) {
        // convert the byte array back to a String
        int startOfSegment = reverse ? startOffset - length + 1 : startOffset;
        String bytesToString = new String(buffer, startOfSegment, length, encoding);
        if (!bytesToString.contains(delimiter)) {
            // didn't find the delimiter.
            return -1;
        }

        // the index is returned, which is 0 based, so our loop must include the zero case.
        int numCharsToDelim = reverse ? bytesToString.lastIndexOf(delimiter) : bytesToString.indexOf(delimiter);
        int toReturn = 0;
        for (int i = 0; i <= numCharsToDelim; i++) {
            toReturn += Character.toString(bytesToString.charAt(startOfSegment + i)).getBytes(encoding).length;
        }

        // we get the total number of bytes, but we want to return the index (which starts at 0)
        // so we subtract 1 from the total number of bytes to get the final byte index.
        return toReturn - 1;
    }

    //endOffset is a 'sentinel' value; we use that to figure out when to stop searching
    int endOffset = reverse ? startOffset - length : startOffset + length;

    // if we are starting at the end, we need to move toward the front enough to grab the right number of bytes
    startOffset = reverse ? startOffset - (bytesPerChar - 1) : startOffset;

    if (startOffset < 0 || startOffset >= buffer.length) {
        throw new IndexOutOfBoundsException(
                "Given start offset is outside the bounds of the given buffer. In reverse cases, the start offset is modified to ensure we check the full size of the last character");
    }

    // make sure that the length we are traversing is at least as long as a single character
    if (length < bytesPerChar) {
        throw new IllegalArgumentException(
                "length must be at least as long as the length, in bytes, of a single character");
    }

    if (endOffset < -1 || endOffset > buffer.length) {
        throw new IndexOutOfBoundsException(
                "Given combination of startOffset and length would execute the search outside the bounds of the given buffer.");
    }

    int bufferEndOffset = reverse ? startOffset : startOffset + length;
    int result = -1;
    for (int charPos = startOffset; reverse ? charPos != endOffset
            : charPos + bytesPerChar - 1 < endOffset; charPos = reverse ? charPos - 1 : charPos + 1) {
        char c;
        if (bytesPerChar == 1) {
            c = (char) buffer[charPos];
        } else {
            String temp = new String(buffer, charPos, bytesPerChar, encoding);
            if (StringUtils.isEmpty(temp)) {
                continue;
            } else {
                c = temp.toCharArray()[0];
            }
        }

        if (isNewline(c, delimiter)) {
            result = charPos + bytesPerChar - 1;
            break;
        }
    }

    if ((delimiter == null || StringUtils.isEmpty(delimiter)) && !reverse
            && result < bufferEndOffset - bytesPerChar) {
        char c;
        if (bytesPerChar == 1) {
            c = (char) buffer[result + bytesPerChar];
        } else {
            String temp = new String(buffer, result + 1, bytesPerChar, encoding);
            if (StringUtils.isEmpty(temp)) {
                // this can occur if the number of bytes for characters in the string result in an empty string (an invalid code for the given encoding)
                // in this case, that means that we are done for the default delimiter.
                return result;
            } else {
                c = temp.toCharArray()[0];
            }
        }

        if (isNewline(c, delimiter)) {
            //we originally landed on a \r character; if we have a \r\n character, advance one position to include that
            result += bytesPerChar;
        }
    }

    return result;
}

From source file:libepg.epg.util.datetime.DateTimeFieldConverter.java

private static Map<HMS_KEY, Integer> BcdTimeToMap(byte[] hms) throws ParseException {
    Map<HMS_KEY, Integer> ret = new HashMap<>();
    if (hms.length != 3) {
        throw new IndexOutOfBoundsException(
                "?????3????????"
                        + " ?=" + Hex.encodeHexString(hms));
    }//from  ww  w  .j  a  va2  s . com

    //ARIB????????????????
    if (Arrays.equals(hms, UNDEFINED_BCD_TIME_BLOCK.getData())) {
        throw new ParseException("???????????" + " ?="
                + Hex.encodeHexString(hms), 0);
    }
    Object[] parameters = null;

    final int hour = new BCD(hms[0]).getDecimal();
    final int minute = new BCD(hms[1]).getDecimal();
    final int second = new BCD(hms[2]).getDecimal();
    CHECK: {
        final Range<Integer> HOUR_RANGE = Range.between(0, 23);

        if (!HOUR_RANGE.contains(hour)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", hour };
            break CHECK;
        }

        final Range<Integer> MINUTE_AND_SECOND_RANGE = Range.between(0, 59);

        if (!MINUTE_AND_SECOND_RANGE.contains(minute)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", minute };
            break CHECK;
        }

        if (!MINUTE_AND_SECOND_RANGE.contains(second)) {
            parameters = new Object[] { Hex.encodeHexString(hms), "", second };
            break CHECK;
        }
    }

    if (parameters != null) {
        MessageFormat msg = new MessageFormat(
                "????????????={0} ={1} ={2}");
        throw new ParseException(msg.format(parameters), 0);
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("hour=" + hour + " minute=" + minute + " second=" + second);
    }

    ret.put(HMS_KEY.HOUR, hour);
    ret.put(HMS_KEY.MINUTE, minute);
    ret.put(HMS_KEY.SECOND, second);

    return ret;
}

From source file:com.evolveum.midpoint.prism.xjc.PrismContainerArrayList.java

private void testIndex(int i) {
    if (i < 0 || i >= getValues().size()) {
        throw new IndexOutOfBoundsException(
                "Can't get index '" + i + "', values size is '" + getValues().size() + "'.");
    }//from  w ww . j a v  a 2s. c om
}

From source file:bulat.diet.helper_couch.common.data.ExampleSectionExpandableDataProvider.java

@Override
public ChildData getChildItem(int groupPosition, int childPosition) {
    if (groupPosition < 0 || groupPosition >= getGroupCount()) {
        throw new IndexOutOfBoundsException("groupPosition = " + groupPosition);
    }/*from ww w  .  ja va  2 s  . co m*/

    final List<ChildData> children = mData.get(groupPosition).second;

    if (childPosition < 0 || childPosition >= children.size()) {
        throw new IndexOutOfBoundsException("childPosition = " + childPosition);
    }

    return children.get(childPosition);
}

From source file:net.librec.recommender.item.RecommendedItemListTestCase.java

public static void testSparseMatrixAndRecommender() {
    Table<Integer, Integer, Double> table = HashBasedTable.create();
    table.put(1, 2, 3.0);/*from  w  w  w .jav a 2  s.co  m*/
    table.put(3, 4, 3.0);
    table.put(5, 2, 3.0);
    table.put(4, 6, 3.0);
    SparseMatrix testMatrix = new SparseMatrix(6, 7, table);
    for (MatrixEntry matrixEntry : testMatrix) {
        System.out.println(matrixEntry.row() + " " + matrixEntry.column() + " " + matrixEntry.get());
    }
    System.out.println();

    int numUsers = 6;
    RecommendedItemList recommendedList = new RecommendedItemList(numUsers - 1, numUsers);

    for (MatrixEntry matrixEntry : testMatrix) {
        int userIdx = matrixEntry.row();
        int itemIdx = matrixEntry.column();
        double predictRating = 3.0;
        if (Double.isNaN(predictRating)) {
            predictRating = 2.0;
        }
        recommendedList.addUserItemIdx(userIdx, itemIdx, predictRating);
    }

    Iterator<MatrixEntry> testMatrixIter = testMatrix.iterator();
    Iterator<UserItemRatingEntry> recommendedEntryIter = recommendedList.entryIterator();

    while (testMatrixIter.hasNext()) {

        if (recommendedEntryIter.hasNext()) {

            MatrixEntry testMatrixEntry = testMatrixIter.next();
            UserItemRatingEntry userItemRatingEntry = recommendedEntryIter.next();

            System.out.println(
                    testMatrixEntry.row() + " " + testMatrixEntry.column() + " " + testMatrixEntry.get());
            System.out.println(userItemRatingEntry.getUserIdx() + " " + userItemRatingEntry.getItemIdx() + " "
                    + userItemRatingEntry.getValue());

            if (testMatrixEntry.row() == userItemRatingEntry.getUserIdx()
                    && testMatrixEntry.column() == userItemRatingEntry.getItemIdx()) {
            } else {
                throw new IndexOutOfBoundsException("index of recommendedList does not equal testMatrix index");
            }

        } else {
            throw new IndexOutOfBoundsException(
                    "index size of recommendedList does not equal testMatrix index size");
        }
    }
}

From source file:ru.jts_dev.common.packets.IncomingMessageWrapper.java

public final <E extends Enum<?>> E readIntAs(final Class<E> enumClass) {
    final int value = readInt();

    if (value < 0 || value > enumClass.getEnumConstants().length)
        throw new IndexOutOfBoundsException(
                "value " + value + " not in enum constants of " + enumClass.getName());

    return enumClass.getEnumConstants()[value];
}

From source file:io.horizondb.io.files.DirectFileDataInput.java

/**
 * {@inheritDoc}//  w ww . j  a v  a2s.  c  om
 */
@Override
public final DirectFileDataInput skipBytes(int numberOfBytes) throws IOException {

    isTrue(numberOfBytes >= 0, "The number of bytes to skip must be greater or equals to zero");

    int numberOfByteToRead = numberOfBytes;

    try {

        while (numberOfByteToRead > 0) {
            if (!this.buffer.hasRemaining()) {
                readData();
            }
            this.buffer.get();
            numberOfByteToRead--;
        }

    } catch (BufferUnderflowException e) {

        throw new IndexOutOfBoundsException(
                "Index: " + (getPosition() + numberOfByteToRead) + ", Size: " + size());
    }

    return this;
}

From source file:ru.jts_dev.authserver.util.Encoder.java

public ByteBuf appendChecksum(ByteBuf buf) {
    if (buf.readableBytes() % 4 != 0) {
        throw new IndexOutOfBoundsException("ByteBuf size must be multiply of 4");
    }//from  w w  w. j av a  2s.c  o  m
    int checksum = 0;
    for (int i = 0; i < buf.readableBytes(); i += 4) {
        checksum ^= buf.getInt(i);
    }

    buf.writeInt(checksum);

    buf.writeZero(4); // for blowfish block

    return buf;
}

From source file:au.org.ala.delta.editor.slotfile.model.SlotFileDataSet.java

@Override
protected Item doGetItem(int number) {
    synchronized (_vop) {
        if (number > getMaximumNumberOfItems()) {
            throw new IndexOutOfBoundsException("No such Item (" + number + ">" + getMaximumNumberOfItems());
        }/*w  ww.j  a va  2  s  .  c  om*/

        int itemId = _vop.getDeltaMaster().uniIdFromItemNo(number);
        VOItemDesc itemDesc = (VOItemDesc) _vop.getDescFromId(itemId);
        VOItemAdaptor adaptor = new VOItemAdaptor(_vop, itemDesc);
        return new Item(adaptor);
    }
}