Example usage for org.apache.commons.lang3 ArrayUtils toPrimitive

List of usage examples for org.apache.commons.lang3 ArrayUtils toPrimitive

Introduction

In this page you can find the example usage for org.apache.commons.lang3 ArrayUtils toPrimitive.

Prototype

public static boolean[] toPrimitive(final Boolean[] array) 

Source Link

Document

Converts an array of object Booleans to primitives.

This method returns null for a null input array.

Usage

From source file:com.mirth.connect.model.transmission.framemode.FrameStreamHandler.java

/**
 * Returns the next message from the stream (could be the entire stream contents or part of a
 * batch)./*www.  j a  v a 2  s.c  o m*/
 * 
 * @return A byte array representing the next whole message in the stream (could be the entire
 *         stream contents or part of a batch), or null if the stream is done. If an IOException
 *         is caught while reading (e.g. a socket timeout) and returnDataOnException is true,
 *         then all bytes accumulated up to that point are returned.
 * @throws IOException
 *             If an IOException is caught while reading (e.g. a socket timeout) and
 *             returnDataOnException is false.
 */
@Override
public byte[] read() throws IOException {
    if (streamDone || inputStream == null) {
        return null;
    }

    capturedBytes = new ByteArrayOutputStream();
    List<Byte> firstBytes = new ArrayList<Byte>();
    // A List is used here to allow the buffer to simulate a "shifting window" of potential bytes.
    endBytesBuffer = new ArrayList<Byte>();

    try {
        // Skip to the beginning of the message
        if (checkStartOfMessageBytes) {
            int i = 0;

            while (i < startOfMessageBytes.length) {
                currentByte = inputStream.read();
                logger.trace("Checking for start of message bytes, currentByte: " + currentByte);

                if (currentByte != -1) {
                    if (firstBytes.size() < startOfMessageBytes.length) {
                        firstBytes.add((byte) currentByte);
                    }

                    if (currentByte == (int) (startOfMessageBytes[i] & 0xFF)) {
                        i++;
                    } else {
                        i = 0;
                    }
                } else {
                    streamDone = true;
                    if (firstBytes.size() > 0) {
                        throw new FrameStreamHandlerException(true, startOfMessageBytes,
                                ArrayUtils.toPrimitive(firstBytes.toArray(new Byte[0])));
                    } else {
                        // The input stream ended before the begin bytes were detected, so return null
                        return null;
                    }
                }
            }

            // Begin bytes were found
            checkStartOfMessageBytes = false;
        }

        // Allow the handler to initialize anything it needs to (e.g. mark the input stream)
        batchStreamReader.initialize();

        // Iterate while there are still bytes to read, or if we're checking for end bytes and its buffer is not empty
        while ((currentByte = batchStreamReader.getNextByte()) != -1
                || (endOfMessageBytes.length > 0 && !endBytesBuffer.isEmpty())) {
            // If the input stream is done, get the byte from the buffer instead
            if (currentByte == -1) {
                currentByte = endBytesBuffer.remove(0);
                streamDone = true;
            } else {
                lastByte = (byte) currentByte;
            }

            // Check to see if an end frame has been received
            if (endOfMessageBytes.length > 0 && !streamDone) {
                if (endBytesBuffer.size() == endOfMessageBytes.length) {
                    // Shift the buffer window over one, popping the first element and writing it to the output stream
                    capturedBytes.write(endBytesBuffer.remove(0));
                }

                // Add the byte to the buffer
                endBytesBuffer.add((byte) currentByte);

                // Check to see if the current buffer window equals the ending byte sequence
                boolean endBytesFound = true;
                for (int i = 0; i <= endBytesBuffer.size() - 1; i++) {
                    if (endBytesBuffer.get(i) != endOfMessageBytes[i]) {
                        endBytesFound = false;
                        break;
                    }
                }

                if (endBytesFound) {
                    // Ending bytes sequence has been detected
                    streamDone = true;
                    return capturedBytes.toByteArray();
                }
            } else {
                // Add the byte to the main output stream
                capturedBytes.write(currentByte);
            }

            if (!streamDone) {
                // Allow subclass to check the current byte stream and return immediately
                byte[] returnBytes = batchStreamReader.checkForIntermediateMessage(capturedBytes,
                        endBytesBuffer, lastByte);
                if (returnBytes != null) {
                    return returnBytes;
                }
            }
        }
    } catch (Throwable e) {
        if (!returnDataOnException) {
            if (e instanceof IOException) {
                // If an IOException occurred and we're not allowing data to return, throw the exception

                if (checkStartOfMessageBytes && firstBytes.size() > 0) {
                    // At least some bytes have been read, but the start of message bytes were not detected
                    throw new FrameStreamHandlerException(true, startOfMessageBytes,
                            ArrayUtils.toPrimitive(firstBytes.toArray(new Byte[0])), e);
                }
                if (capturedBytes.size() + endBytesBuffer.size() > 0 && endOfMessageBytes.length > 0) {
                    // At least some bytes have been captured, but the end of message bytes were not detected
                    throw new FrameStreamHandlerException(false, endOfMessageBytes, getLastBytes(), e);
                }
                throw (IOException) e;
            } else {
                // If any other Throwable was caught, return null to indicate that we're done
                return null;
            }
        }
    }

    if (endOfMessageBytes.length > 0) {
        // If we got here, then the end of message bytes were not captured
        throw new FrameStreamHandlerException(false, endOfMessageBytes, getLastBytes());
    } else {
        /*
         * If we got here, no end of message bytes were expected, but we should reset the check
         * flag so that the next time a read is performed, it will attempt to capture the
         * starting bytes again.
         */
        checkStartOfMessageBytes = true;
    }

    // Flush the buffer to the main output stream
    for (Byte bufByte : endBytesBuffer) {
        capturedBytes.write(bufByte);
    }

    return capturedBytes.size() > 0 ? capturedBytes.toByteArray() : null;
}

From source file:lockstep.ClientReceivingQueue.java

/**
 * Extract an int array containing the selective ACKs
 * /*from   w  ww  . j a  v  a 2s  .  c  o  m*/
 * @return the int array of selective ACKs
 */
private int[] _getSelectiveACKs() {
    Integer[] selectiveACKsIntegerArray = this.selectiveACKsSet.toArray(new Integer[0]);
    if (selectiveACKsIntegerArray.length > 0) {
        int[] selectiveACKs = ArrayUtils.toPrimitive(selectiveACKsIntegerArray);
        return selectiveACKs;
    } else
        return null;
}

From source file:io.bibleget.BibleGetFrame.java

/**
 *
 * @throws ClassNotFoundException//from  w  w w .  jav  a  2 s.  c  om
 */
private void prepareDynamicInformation() throws ClassNotFoundException {
    biblegetDB = BibleGetDB.getInstance();
    String bibleVersionsStr = biblegetDB.getMetaData("VERSIONS");
    JsonReader jsonReader = Json.createReader(new StringReader(bibleVersionsStr));
    JsonObject bibleVersionsObj = jsonReader.readObject();
    Set<String> versionsabbrev = bibleVersionsObj.keySet();
    bibleVersions = new BasicEventList<>();
    if (!versionsabbrev.isEmpty()) {
        for (String s : versionsabbrev) {
            String versionStr = bibleVersionsObj.getString(s); //store these in an array
            String[] array;
            array = versionStr.split("\\|");
            bibleVersions.add(new BibleVersion(s, array[0], array[1],
                    StringUtils.capitalize(new Locale(array[2]).getDisplayLanguage())));
        }
    }

    List<String> preferredVersions = new ArrayList<>();
    String retVal = (String) biblegetDB.getOption("PREFERREDVERSIONS");
    if (null == retVal) {
        //System.out.println("Attempt to retrieve PREFERREDVERSIONS from the Database resulted in null value");
    } else {
        //System.out.println("Retrieved PREFERREDVERSIONS from the Database. Value is:"+retVal);
        String[] favoriteVersions = StringUtils.split(retVal, ',');
        preferredVersions = Arrays.asList(favoriteVersions);
    }
    if (preferredVersions.isEmpty()) {
        preferredVersions.add("NVBSE");
    }
    List<Integer> preferredVersionsIndices = new ArrayList<>();

    versionsByLang = new SeparatorList<>(bibleVersions, new VersionComparator(), 1, 1000);
    int listLength = versionsByLang.size();
    enabledFlags = new boolean[listLength];
    ListIterator itr = versionsByLang.listIterator();
    while (itr.hasNext()) {
        int idx = itr.nextIndex();
        Object next = itr.next();
        enabledFlags[idx] = !(next.getClass().getSimpleName().equals("GroupSeparator"));
        if (next.getClass().getSimpleName().equals("BibleVersion")) {
            BibleVersion thisBibleVersion = (BibleVersion) next;
            if (preferredVersions.contains(thisBibleVersion.getAbbrev())) {
                preferredVersionsIndices.add(idx);
            }
        }
    }
    indices = ArrayUtils
            .toPrimitive(preferredVersionsIndices.toArray(new Integer[preferredVersionsIndices.size()]));
    //System.out.println("value of indices array: "+Arrays.toString(indices));

}

From source file:com.github.jessemull.microflex.util.BigIntegerUtil.java

/**
 * Converts a list of BigIntegers to an array of bytes.
 * @param    List<BigInteger>    list of BigIntegers
 * @return                       array of bytes
 *//* w w  w  . j  a  va  2  s  .c om*/
public static byte[] toByteArray(List<BigInteger> list) {

    for (BigInteger val : list) {
        if (!OverFlowUtil.byteOverflow(val)) {
            OverFlowUtil.overflowError(val);
        }
    }

    return ArrayUtils.toPrimitive(list.toArray(new Byte[list.size()]));

}

From source file:com.github.jessemull.microflex.util.BigDecimalUtil.java

/**
 * Converts a list of BigDecimals to an array of bytes.
 * @param    List<BigDecimal>    list of BigDecimals
 * @return                       array of bytes
 *//*from w w w.  j  av a2  s.  co  m*/
public static byte[] toByteArray(List<BigDecimal> list) {

    for (BigDecimal val : list) {
        if (!OverFlowUtil.byteOverflow(val)) {
            OverFlowUtil.overflowError(val);
        }
    }

    return ArrayUtils.toPrimitive(list.toArray(new Byte[list.size()]));

}

From source file:ca.mcgill.cs.creco.logic.NumericCorrelator.java

private double computeCorrelation(String pFirstAttributeId, String pSecondAttributeId, double pThreshold) {
    List<Double> firstValues = new ArrayList<Double>();
    List<Double> secondValues = new ArrayList<Double>();

    double existingCount = 0.0;
    double nonNumericCount = 0.0;

    for (Product product : aCategory.getProducts()) {
        Attribute firstAttribute = product.getAttribute(pFirstAttributeId);
        Attribute secondAttribute = product.getAttribute(pSecondAttributeId);

        // Skip the product if it's missing either attribute
        if (missing(firstAttribute) || missing(secondAttribute)) {
            continue;
        }/*from   w ww  .j a va 2  s.com*/
        //add if the value is not missing
        existingCount++;
        //if the attribute is not numeric keep count
        if (!firstAttribute.getTypedValue().isNumeric() || !secondAttribute.getTypedValue().isNumeric()) {
            nonNumericCount++;
        }
        //else add the values to the correlation array
        else {
            double firstValue = firstAttribute.getTypedValue().getNumeric();
            double secondValue = secondAttribute.getTypedValue().getNumeric();

            if (firstValue > 0) {
                firstValues.add(firstValue);
                secondValues.add(secondValue);
            }
        }

    }
    double ratio = 1 - nonNumericCount / existingCount;
    if (ratio < pThreshold) {
        throw new IllegalArgumentException("Threshold for correlation was not met: " + ratio + "<" + pThreshold
                + " count: " + existingCount + " NNcount: " + nonNumericCount);
    }

    double[] firstArray = ArrayUtils.toPrimitive(firstValues.toArray(new Double[0]));
    double[] secondArray = ArrayUtils.toPrimitive(secondValues.toArray(new Double[0]));

    PearsonsCorrelation pearsonsCorrelation = new PearsonsCorrelation();

    if (firstArray.length < 2 || secondArray.length < 2) {
        return 0;
    }
    return pearsonsCorrelation.correlation(firstArray, secondArray);
}

From source file:net.larry1123.elec.util.test.config.AbstractConfigTest.java

public void DoubleArrayTest(String fieldName, Field testField) {
    try {/*from   w ww  .ja v  a 2s  . c  om*/
        double[] testFieldValue = ArrayUtils.toPrimitive((Double[]) testField.get(getConfigBase()));
        Assert.assertTrue(ArrayUtils.isEquals(getPropertiesFile().getDoubleArray(fieldName), testFieldValue));
    } catch (IllegalAccessException e) {
        assertFailFieldError(fieldName);
    }
}

From source file:com.vsthost.rnd.commons.math.ext.linear.DMatrixUtils.java

/**
 * Creates a new array by selecting those elements marked as true in the predicate array.
 *
 * @param values The array where the elements are going to be selected from.
 * @param predicate The selection mapper.
 * @return The new array with selected items.
 *//*from  w w  w  . j a  v a 2s. c  om*/
public static double[] selectByPredicate(double[] values, Boolean[] predicate) {
    return DMatrixUtils.selectByPredicate(values, ArrayUtils.toPrimitive(predicate));
}

From source file:net.larry1123.elec.util.test.config.AbstractConfigTest.java

public void DoubleArrayListTest(String fieldName, Field testField) {
    try {// www .  j ava 2 s . c o  m
        //noinspection unchecked,unchecked
        double[] testFieldValue = ArrayUtils.toPrimitive(((ArrayList<Double>) testField.get(getConfigBase()))
                .toArray(new Double[((ArrayList<Double>) testField.get(getConfigBase())).size()]));
        Assert.assertTrue(ArrayUtils.isEquals(getPropertiesFile().getDoubleArray(fieldName), testFieldValue));
    } catch (IllegalAccessException e) {
        assertFailFieldError(fieldName);
    }
}

From source file:com.github.jessemull.microflex.util.DoubleUtil.java

/**
 * Converts a list of doubles to an array of bytes.
 * @param    List<Double>    list of doubles
 * @return                   array of bytes
 *///from   w  w w  .  java  2s .  c o m
public static byte[] toByteArray(List<Double> list) {

    for (Double val : list) {
        if (!OverFlowUtil.byteOverflow(val)) {
            OverFlowUtil.overflowError(val);
        }
    }

    return ArrayUtils.toPrimitive(list.toArray(new Byte[list.size()]));

}