Example usage for org.apache.commons.lang ArrayUtils subarray

List of usage examples for org.apache.commons.lang ArrayUtils subarray

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils subarray.

Prototype

public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) 

Source Link

Document

Produces a new boolean array containing the elements between the start and end indices.

Usage

From source file:org.jahia.utils.zip.legacy.ZipInputStream.java

private String getUTF8StringOurs(byte[] b, int off, int len) {
    try {// ww w . java2s .c  o m
        if (!utfFailed) {
            String r = new String(b, off, len, "UTF-8");
            byte[] b2 = r.getBytes("UTF-8");
            if (ArrayUtils.isEquals(b2, ArrayUtils.subarray(b, 0, b2.length))) {
                return r;
            } else {
                utfFailed = true;
            }
        }
        return new String(b, off, len, encoding);
    } catch (UnsupportedEncodingException e) {
        return new String(b, off, len);
    }
}

From source file:org.jahia.utils.zip.ZipInputStream.java

private String getUTF8String(byte[] b, int off, int len) {
    try {//from ww w  .  j ava 2  s . c  o  m
        if (!utfFailed) {
            String r = new String(b, off, len, "UTF-8");
            byte[] b2 = r.getBytes("UTF-8");
            if (ArrayUtils.isEquals(b2, ArrayUtils.subarray(b, 0, b2.length))) {
                return r;
            } else {
                utfFailed = true;
            }
        }
        return new String(b, off, len, encoding);
    } catch (UnsupportedEncodingException e) {
        return new String(b, off, len);
    }
}

From source file:org.jnap.core.persistence.hibernate.DynaQueryBuilder.java

Object[] getPropertyValues(int size) {
    if ((propertyValueIndex + size) <= this.queryParams.length) {
        Object[] values = ArrayUtils.subarray(this.queryParams, propertyValueIndex, propertyValueIndex + size);
        propertyValueIndex += size;//from   w w w . j  a  va  2  s  .  c  om
        return values;
    } else {
        throw new QueryException(
                format("The number of parameters ({0}) does not satisfy " + "QueryMethod expression",
                        Integer.toString(this.queryParams.length)),
                this.dynaQuery);
    }
}

From source file:org.jspringbot.keyword.test.data.TestDataResourceState.java

public void parse() throws IOException {
    InputStreamReader isr = null;
    headers = null;/* w w  w  .j a  v  a  2 s.c o  m*/
    headerLine = null;
    totalSize = 0;
    int currentIndex = 0;
    baseKey = name + "/";

    try {
        isr = new InputStreamReader(resource.getInputStream());
        CSVReader reader = new CSVReader(isr);

        String[] nextLine;
        TestData currentTestData = null;
        while ((nextLine = reader.readNext()) != null) {
            if (nextLine.length == 0) {
                continue;
            }

            // retrieve csv header
            if (headers == null) {
                headerLine = new LinkedList<String>();
                headers = new HashMap<String, Integer>(nextLine.length);
                for (int i = 0; i < nextLine.length; i++) {
                    headers.put(nextLine[i].toLowerCase(), i);
                    headerLine.add(nextLine[i].toUpperCase());
                }
                continue;
            }

            if (StringUtils.isNotBlank(nextLine[0])) {
                if (currentTestData != null) {
                    cache.put(new Element(buildKey(currentIndex++), currentTestData));
                }

                currentTestData = new TestData(Arrays.asList(nextLine));
            } else if (currentTestData != null) {
                currentTestData.addContent(
                        Arrays.asList((String[]) ArrayUtils.subarray(nextLine, 1, nextLine.length)));
            }
        }

        if (currentTestData != null) {
            cache.put(new Element(buildKey(currentIndex), currentTestData));
        }

        totalSize = currentIndex + 1;
    } finally {
        IOUtils.closeQuietly(isr);
    }
}

From source file:org.jumpmind.symmetric.io.data.writer.DatabaseWriterTest.java

@Test
public void testUpdateNotExisting() throws Exception {
    String id = getNextId();/*from w w  w  . jav  a2 s .c o m*/
    String[] values = { id, "it's /a/  string", "it's  -not-  null", "You're a \"character\"", "Where are you?",
            "2007-12-31 02:33:45.000", "2007-12-31 23:59:59.000", "1", "13", "9.95", "-0.0747" };
    String[] expectedValues = (String[]) ArrayUtils.subarray(values, 0, values.length);
    massageExpectectedResultsForDialect(expectedValues);
    writeData(new CsvData(DataEventType.UPDATE, new String[] { id }, values), expectedValues);
}

From source file:org.jumpmind.symmetric.service.impl.AbstractDataLoaderServiceTest.java

@Test
public void test02Statistics() throws Exception {
    Level old = setLoggingLevelForTest(Level.FATAL);
    String[] updateValues = new String[TEST_COLUMNS.length + 1];
    updateValues[0] = updateValues[updateValues.length - 1] = getNextId();
    updateValues[2] = updateValues[4] = "required string";
    String[] insertValues = (String[]) ArrayUtils.subarray(updateValues, 0, updateValues.length - 1);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    CsvWriter writer = getWriter(out);//from   w  w  w .  ja  va 2s .co  m
    writer.writeRecord(new String[] { CsvConstants.NODEID, TestConstants.TEST_CLIENT_EXTERNAL_ID });
    writer.writeRecord(new String[] { CsvConstants.CHANNEL, TestConstants.TEST_CHANNEL_ID });
    String nextBatchId = getNextBatchId();
    writer.writeRecord(new String[] { CsvConstants.BATCH, nextBatchId });
    writeTable(writer, TEST_TABLE, TEST_KEYS, TEST_COLUMNS);

    // Update becomes fallback insert
    writer.write(CsvConstants.UPDATE);
    writer.writeRecord(updateValues, true);

    // Insert becomes fallback update
    writer.write(CsvConstants.INSERT);
    writer.writeRecord(insertValues, true);

    // Insert becomes fallback update
    writer.write(CsvConstants.INSERT);
    writer.writeRecord(insertValues, true);

    // Clean insert
    insertValues[0] = getNextId();
    writer.write(CsvConstants.INSERT);
    writer.writeRecord(insertValues, true);

    // Delete affects no rows
    writer.writeRecord(new String[] { CsvConstants.DELETE, getNextId() }, true);
    writer.writeRecord(new String[] { CsvConstants.DELETE, getNextId() }, true);
    writer.writeRecord(new String[] { CsvConstants.DELETE, getNextId() }, true);

    // Failing statement
    insertValues[0] = getNextId();
    insertValues[5] = "i am an invalid date";
    writer.write(CsvConstants.INSERT);
    writer.writeRecord(insertValues, true);

    writer.writeRecord(new String[] { CsvConstants.COMMIT, nextBatchId });
    writer.close();
    load(out);

    IncomingBatch batch = getIncomingBatchService().findIncomingBatch(batchId,
            TestConstants.TEST_CLIENT_EXTERNAL_ID);
    assertNotNull(batch);
    assertEquals(batch.getStatus(), IncomingBatch.Status.ER, "Wrong status. " + printDatabase());
    assertEquals(batch.getFailedRowNumber(), 8l,
            "Wrong failed row number. " + batch.getSqlMessage() + ". " + printDatabase());
    assertEquals(batch.getByteCount(), 496l, "Wrong byte count. " + printDatabase());
    assertEquals(batch.getStatementCount(), 8l, "Wrong statement count. " + printDatabase());
    assertEquals(batch.getFallbackInsertCount(), 1l, "Wrong fallback insert count. " + printDatabase());
    assertEquals(batch.getFallbackUpdateCount(), 2l, "Wrong fallback update count. " + printDatabase());
    assertEquals(batch.getMissingDeleteCount(), 3l, "Wrong missing delete count. " + printDatabase());
    setLoggingLevelForTest(old);
}

From source file:org.kuali.kfs.module.cab.service.impl.CapitalAssetBuilderModuleServiceImpl.java

/**
 * Validates field requirement by chart for one or multiple system types.
 *
 * @param systemType//from   w  ww . ja  v a2s.co  m
 * @param systemState
 * @param capitalAssetSystems
 * @param capitalAssetItems
 * @param chartCode
 * @param parameterName
 * @param parameterValueString
 * @return
 */
protected boolean validateFieldRequirementByChartForOneOrMultipleSystemType(String systemType,
        String systemState, List<CapitalAssetSystem> capitalAssetSystems,
        List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName,
        String parameterValueString) {
    boolean valid = true;
    boolean needValidation = (parameterEvaluatorService
            .getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName,
                    chartCode)
            .evaluationSucceeds());

    if (needValidation) {
        if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
            return validateCapitalAssetLocationAddressFieldsOneOrMultipleSystemType(capitalAssetSystems);
        }
        String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES
                .get(parameterName);
        if (mappedName != null) {
            // Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
            // to validate any further.
            String availableValue = getValueFromAvailabilityMatrix(mappedName, systemType, systemState);
            if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
                return true;
            }

            // capitalAssetTransactionType field is off the item
            if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
                String[] mappedNames = { PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS, mappedName };

                for (PurchasingCapitalAssetItem item : capitalAssetItems) {
                    StringBuffer keyBuffer = new StringBuffer("document."
                            + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "["
                            + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
                    valid &= validateFieldRequirementByChartHelper(item,
                            ArrayUtils.subarray(mappedNames, 1, mappedNames.length), keyBuffer,
                            item.getPurchasingItem().getItemLineNumber());
                }
            }
            // all the other fields are off the system.
            else {
                List<String> mappedNamesList = new ArrayList<String>();
                mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS);
                if (mappedName.indexOf(".") < 0) {
                    mappedNamesList.add(mappedName);
                } else {
                    mappedNamesList.addAll(mappedNameSplitter(mappedName));
                }
                // For One system type, we would only have 1 CapitalAssetSystem, however, for multiple we may have more than
                // one systems in the future. Either way, this for loop should allow both the one system and multiple system
                // types to work fine.
                int count = 0;
                for (CapitalAssetSystem system : capitalAssetSystems) {
                    StringBuffer keyBuffer = new StringBuffer(
                            "document." + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEMS + "["
                                    + new Integer(count) + "].");
                    valid &= validateFieldRequirementByChartHelper(system,
                            ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()),
                            keyBuffer, null);
                    count++;
                }
            }
        }
    }
    return valid;
}

From source file:org.kuali.kfs.module.cab.service.impl.CapitalAssetBuilderModuleServiceImpl.java

/**
 * Validates the field requirement by chart for individual system type.
 *
 * @param systemState/* w  w w  .  j  a va 2s.c  o  m*/
 * @param capitalAssetItems
 * @param chartCode
 * @param parameterName
 * @param parameterValueString
 * @return
 */
protected boolean validateFieldRequirementByChartForIndividualSystemType(String systemState,
        List<PurchasingCapitalAssetItem> capitalAssetItems, String chartCode, String parameterName,
        String parameterValueString) {
    boolean valid = true;
    boolean needValidation = (parameterEvaluatorService
            .getParameterEvaluator(KfsParameterConstants.CAPITAL_ASSET_BUILDER_DOCUMENT.class, parameterName,
                    chartCode)
            .evaluationSucceeds());

    if (needValidation) {
        if (parameterName.startsWith("CHARTS_REQUIRING_LOCATIONS_ADDRESS")) {
            return validateCapitalAssetLocationAddressFieldsForIndividualSystemType(capitalAssetItems);
        }
        String mappedName = PurapConstants.CAMS_REQUIREDNESS_FIELDS.REQUIREDNESS_FIELDS_BY_PARAMETER_NAMES
                .get(parameterName);
        if (mappedName != null) {
            // Check the availability matrix here, if this field doesn't exist according to the avail. matrix, then no need
            // to validate any further.
            String availableValue = getValueFromAvailabilityMatrix(mappedName,
                    PurapConstants.CapitalAssetSystemTypes.INDIVIDUAL, systemState);
            if (availableValue.equals(PurapConstants.CapitalAssetAvailability.NONE)) {
                return true;
            }

            // capitalAssetTransactionType field is off the item
            List<String> mappedNamesList = new ArrayList<String>();

            if (mappedName.equals(PurapPropertyConstants.CAPITAL_ASSET_TRANSACTION_TYPE_CODE)) {
                mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
                mappedNamesList.add(mappedName);

            }
            // all the other fields are off the system which is off the item
            else {
                mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS);
                mappedNamesList.add(PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_SYSTEM);
                if (mappedName.indexOf(".") < 0) {
                    mappedNamesList.add(mappedName);
                } else {
                    mappedNamesList.addAll(mappedNameSplitter(mappedName));
                }
            }
            // For Individual system type, we'll always iterate through the item, then if the field is off the system, we'll get
            // it through
            // the purchasingCapitalAssetSystem of the item.
            for (PurchasingCapitalAssetItem item : capitalAssetItems) {
                StringBuffer keyBuffer = new StringBuffer("document."
                        + PurapPropertyConstants.PURCHASING_CAPITAL_ASSET_ITEMS + "["
                        + new Integer(item.getPurchasingItem().getItemLineNumber().intValue() - 1) + "].");
                valid &= validateFieldRequirementByChartHelper(item,
                        ArrayUtils.subarray(mappedNamesList.toArray(), 1, mappedNamesList.size()), keyBuffer,
                        item.getPurchasingItem().getItemLineNumber());
            }
        }
    }
    return valid;
}

From source file:org.kuali.kfs.module.cab.service.impl.CapitalAssetBuilderModuleServiceImpl.java

/**
 * Validates the field requirement by chart recursively and give error messages when it returns false.
 *
 * @param bean        The object to be used to obtain the property value
 * @param mappedNames The array of Strings which when combined together, they form the field property
 * @param errorKey    The error key to be used for adding error messages to the error map.
 * @param itemNumber  The Integer that represents the item number that we're currently iterating.
 * @return true if it passes the validation.
 *///from   w w  w .ja va2s  .co  m
protected boolean validateFieldRequirementByChartHelper(Object bean, Object[] mappedNames,
        StringBuffer errorKey, Integer itemNumber) {
    boolean valid = true;
    Object value = ObjectUtils.getPropertyValue(bean, (String) mappedNames[0]);
    if (ObjectUtils.isNull(value)) {
        errorKey.append(mappedNames[0]);
        String fieldName = dataDictionaryService.getAttributeErrorLabel(bean.getClass(),
                (String) mappedNames[0]);
        if (itemNumber != null) {
            fieldName = fieldName + " in Item " + itemNumber;
        }
        GlobalVariables.getMessageMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED,
                fieldName);
        return false;
    } else if (value instanceof Collection) {
        if (((Collection) value).isEmpty()) {
            // if this collection doesn't contain anything, when it's supposed to contain some strings with values, return
            // false.
            errorKey.append(mappedNames[0]);
            String mappedNameStr = (String) mappedNames[0];
            String methodToInvoke = "get" + (mappedNameStr.substring(0, 1)).toUpperCase()
                    + mappedNameStr.substring(1, mappedNameStr.length() - 1) + "Class";
            Class offendingClass;
            try {
                offendingClass = (Class) bean.getClass().getMethod(methodToInvoke, (Class[]) null).invoke(bean,
                        (Object[]) null);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
            org.kuali.rice.krad.datadictionary.BusinessObjectEntry boe = dataDictionaryService
                    .getDataDictionary().getBusinessObjectEntry(offendingClass.getSimpleName());
            List<AttributeDefinition> offendingAttributes = boe.getAttributes();
            AttributeDefinition offendingAttribute = offendingAttributes.get(0);
            String fieldName = dataDictionaryService.getAttributeShortLabel(offendingClass,
                    offendingAttribute.getName());
            GlobalVariables.getMessageMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED,
                    fieldName);
            return false;
        }
        int count = 0;
        for (Iterator iter = ((Collection) value).iterator(); iter.hasNext();) {
            errorKey.append(mappedNames[0] + "[" + count + "].");
            count++;
            valid &= validateFieldRequirementByChartHelper(iter.next(),
                    ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
        }
        return valid;
    } else if (StringUtils.isBlank(value.toString())) {
        errorKey.append(mappedNames[0]);
        GlobalVariables.getMessageMap().putError(errorKey.toString(), KFSKeyConstants.ERROR_REQUIRED,
                (String) mappedNames[0]);
        return false;
    } else if (mappedNames.length > 1) {
        // this means we have not reached the end of a single field to be traversed yet, so continue with the recursion.
        errorKey.append(mappedNames[0]).append(".");
        valid &= validateFieldRequirementByChartHelper(value,
                ArrayUtils.subarray(mappedNames, 1, mappedNames.length), errorKey, itemNumber);
        return valid;
    } else {
        return true;
    }
}

From source file:org.lexevs.dao.database.prefix.CyclingCharDbPrefixGenerator.java

/**
 * Adjust length.//from   w ww  .j ava 2  s. c  om
 * 
 * @param chars the chars
 * 
 * @return the char[]
 */
protected char[] adjustLength(char[] chars) {
    if (chars.length < prefixLengthLimit) {
        chars = adjustLength(ArrayUtils.add(chars, FIRST_CHARACTER));
    } else if (chars.length > prefixLengthLimit) {
        chars = ArrayUtils.subarray(chars, 0, prefixLengthLimit);
    }
    return chars;
}