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

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

Introduction

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

Prototype

public static short[] add(short[] array, short element) 

Source Link

Document

Copies the given array and adds the given element at the end of the new array.

Usage

From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java

/**
 * Copy source bean collection properties of type bean to target bean as
 * detached bean collections//from   w  w w.ja va  2 s .c o m
 * 
 * @param sourceBean
 *            Source Bean
 * @param targetBean
 *            Target Bean
 * @param childrenBeanConverters
 *            List of converters needed to convert source bean childs of
 *            type bean collection to target bean childs of type bean
 *            collection
 * @param sourceFields
 *            Fields of source Bean
 * @throws Exception
 */
private static void convertBeanCollectionFields(AbstractBean sourceBean, AbstractBean targetBean,
        IBeanConverter[] childrenBeanConverters, Field[] sourceFields) throws Exception {

    // Arrays to hold bean collection field names, target collection types,
    // source collection parameter types and target collection parameter
    // types
    String[] beanCollectionFieldNames = new String[0];
    Type[] targetFieldTypes = new Type[0];
    Type[] sourceFieldParameterTypes = new Type[0];
    Type[] targetFieldParameterTypes = new Type[0];

    // For each source field...
    for (Field field : sourceFields) {
        // If source field is a collection...
        if (Collection.class.isAssignableFrom(field.getType())) {
            // Get Field (Remember is a collection) parameters
            Type[] sourceFieldParameters = ((ParameterizedType) field.getGenericType())
                    .getActualTypeArguments();
            // If field is a collection of something extending
            // AbstractBean...
            if (sourceFieldParameters.length == 1
                    && AbstractBean.class.isAssignableFrom((Class<?>) sourceFieldParameters[0])) {
                // If target field is a collection
                if (Collection.class
                        .isAssignableFrom(targetBean.getClass().getDeclaredField(field.getName()).getType())) {
                    // Get target field parameter types
                    Type[] targetFieldParameters = ((ParameterizedType) targetBean.getClass()
                            .getDeclaredField(field.getName()).getGenericType()).getActualTypeArguments();
                    // If target field is a collection of something
                    // extending
                    // AbstractBean...
                    if (targetFieldParameters.length == 1
                            && AbstractBean.class.isAssignableFrom((Class<?>) targetFieldParameters[0])) {
                        // Fill Arrays with name, source field type, target
                        // type and target
                        // parameter type
                        beanCollectionFieldNames = (String[]) ArrayUtils.add(beanCollectionFieldNames,
                                field.getName());
                        targetFieldTypes = (Type[]) ArrayUtils.add(targetFieldTypes,
                                targetBean.getClass().getDeclaredField(field.getName()).getType());
                        sourceFieldParameterTypes = (Type[]) ArrayUtils.add(sourceFieldParameterTypes,
                                sourceFieldParameters[0]);
                        targetFieldParameterTypes = (Type[]) ArrayUtils.add(targetFieldParameterTypes,
                                targetFieldParameters[0]);

                    } else {
                        throw new Exception("Target collection parameter type mismatch");
                    }
                } else {
                    throw new Exception("Target parameter type mismatch");
                }
            }
        }
    }

    // For each field with collection of bean type...
    for (int i = 0; i < beanCollectionFieldNames.length; i++) {
        String beanCollectionFieldName = beanCollectionFieldNames[i];
        Type targetFieldType = targetFieldTypes[i];
        Type sourceFieldParameterType = sourceFieldParameterTypes[i];
        Type targetFieldParameterType = targetFieldParameterTypes[i];

        // Select the appropiate converter...
        IBeanConverter converter = getConverter(childrenBeanConverters, sourceFieldParameterType,
                targetFieldParameterType);

        // Create a target detached (LazyArrayList) collection using the
        // source collection, the target parameter type y the converter...
        @SuppressWarnings("unchecked")
        IndirectArrayList<AbstractBean, AbstractBean> lazyCollection = new IndirectArrayList<AbstractBean, AbstractBean>(
                (List<AbstractBean>) getGetterMethod(beanCollectionFieldName, sourceBean).invoke(sourceBean),
                (Class<AbstractBean>) targetFieldParameterType, converter);
        // Set the detached collection on target bean
        getSetterMethod(beanCollectionFieldName, targetFieldType, targetBean).invoke(targetBean,
                lazyCollection);

    }
}

From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java

/**
 * Copy source bean properties of type bean to target bean as detached beans
 * /*from   w  w w  .j  a  va  2s. c  om*/
 * @param sourceBean
 *            Source Bean
 * @param targetBean
 *            Target Bean
 * @param childrenBeanConverters
 *            List of converters needed to convert source bean children of
 *            type bean to target bean children of type bean
 * @param sourceFields
 *            Fields of source Bean
 * @throws Exception
 */
private static void convertBeanFields(AbstractBean sourceBean, AbstractBean targetBean,
        IBeanConverter[] childrenBeanConverters, Field[] sourceFields) throws Exception {

    // Arrays to hold bean field names, source types and target types
    String[] beanFieldNames = new String[0];
    Type[] sourceFieldTypes = new Type[0];
    Type[] targetFieldTypes = new Type[0];

    // For each source field...
    for (Field field : sourceFields) {
        // If source field is a bean...
        if (AbstractBean.class.isAssignableFrom(field.getType())) {
            // Fill Arrays with name, source field type and target type
            beanFieldNames = (String[]) ArrayUtils.add(beanFieldNames, field.getName());

            sourceFieldTypes = (Type[]) ArrayUtils.add(sourceFieldTypes, field.getType());

            targetFieldTypes = (Type[]) ArrayUtils.add(targetFieldTypes,
                    targetBean.getClass().getDeclaredField(field.getName()).getType());
        }
    }

    // For each field with bean type...
    for (int i = 0; i < beanFieldNames.length; i++) {
        String beanFieldName = beanFieldNames[i];
        Type sourceFieldType = sourceFieldTypes[i];
        Type targetFieldType = targetFieldTypes[i];

        // Select the proper converter...
        IBeanConverter converter = getConverter(childrenBeanConverters, sourceFieldType, targetFieldType);

        // Get the target bean constructor
        @SuppressWarnings("unchecked")
        Constructor<AbstractBean> constructor = ((Class<AbstractBean>) targetFieldType)
                .getConstructor(new Class[] {});
        // Create target child bean
        AbstractBean targetChildBean = constructor.newInstance(new Object[] {});
        // Detach target child bean with source child bean and converter
        ((Detachable) targetChildBean).detach(
                (AbstractBean) getGetterMethod(beanFieldName, sourceBean).invoke(sourceBean), converter);
        // Set the detached target bean
        getSetterMethod(beanFieldName, targetFieldType, targetBean).invoke(targetBean, targetChildBean);

    }
}

From source file:org.appverse.web.framework.backend.api.converters.helpers.ConverterUtils.java

/**
 * Copy source bean single properties to target bean
 * /*from w w w  .  jav a  2s.  co m*/
 * @param source
 *            Source Bean
 * @param target
 *            Target Bean
 * @param sourceFields
 *            Fields of source Bean
 * @throws Exception
 */
private static void copyPlainFields(AbstractBean source, AbstractBean target, Field[] sourceFields)
        throws Exception {
    String[] ignoreProperties = new String[0];

    // For each source field...
    for (Field field : sourceFields) {
        // If source field is a bean...
        if (AbstractBean.class.isAssignableFrom(field.getType())) {
            // Put it in ignore properties
            ignoreProperties = (String[]) ArrayUtils.add(ignoreProperties, field.getName());
        }
    }

    // Copy properties with Spring Framework copy properties
    org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
}

From source file:org.betaconceptframework.astroboa.engine.jcr.util.JcrValueUtils.java

public static void replaceValue(Node node, ItemQName property, Value newValue, Value oldValue,
        Boolean isPropertyMultivalued) throws RepositoryException {

    //Node does not have property
    if (!node.hasProperty(property.getJcrName())) {
        //New Value is null. Do nothing
        if (newValue == null)
            return;

        //Determine if property is multiple, if this info is not provided
        if (isPropertyMultivalued == null) {
            isPropertyMultivalued = propertyIsMultiValued(node, property);

        }//from  ww w. j a  va  2s. c om

        if (isPropertyMultivalued)
            node.setProperty(property.getJcrName(), new Value[] { newValue });
        else
            node.setProperty(property.getJcrName(), newValue);
    } else {
        //Node has property
        Property jcrProperty = node.getProperty(property.getJcrName());

        if (isPropertyMultivalued == null)
            //Determine by property
            isPropertyMultivalued = jcrProperty.getDefinition().isMultiple();

        if (!isPropertyMultivalued) {
            if (oldValue == null || (oldValue != null && oldValue.equals(jcrProperty.getValue()))) {
                //Set newValue only if no old value is provided OR
                //oldValue is provided and it really exists there
                jcrProperty.setValue(newValue);
            }
        } else {

            Value[] values = jcrProperty.getValues();

            //Remove oldValue
            if (oldValue != null) {
                int index = ArrayUtils.indexOf(values, oldValue);
                if (index == ArrayUtils.INDEX_NOT_FOUND)
                    throw new ItemNotFoundException(
                            "Value " + oldValue.getString() + " in property " + jcrProperty.getPath());

                values = (Value[]) ArrayUtils.remove(values, index);
            }

            //Add new value
            if (newValue != null && !ArrayUtils.contains(values, newValue))
                values = (Value[]) ArrayUtils.add(values, newValue);

            //If at the end values array is empty
            //remove property
            if (ArrayUtils.isEmpty(values)) {
                node.setProperty(property.getJcrName(), JcrValueUtils.getJcrNullForMultiValue());
            } else {
                node.setProperty(property.getJcrName(), values);
            }
        }
    }
}

From source file:org.broadinstitute.gatk.tools.walkers.haplotypecaller.LDMerger.java

protected VariantContext createMergedVariantContext(final VariantContext thisVC, final VariantContext nextVC,
        final byte[] ref, final GenomeLoc refLoc) {
    final int thisStart = thisVC.getStart();
    final int nextStart = nextVC.getStart();
    byte[] refBases = new byte[] {};
    byte[] altBases = new byte[] {};
    refBases = ArrayUtils.addAll(refBases, thisVC.getReference().getBases());
    altBases = ArrayUtils.addAll(altBases, thisVC.getAlternateAllele(0).getBases());
    int locus;// w ww.  j  a  v  a 2 s  .c o  m
    for (locus = thisStart + refBases.length; locus < nextStart; locus++) {
        final byte refByte = ref[locus - refLoc.getStart()];
        refBases = ArrayUtils.add(refBases, refByte);
        altBases = ArrayUtils.add(altBases, refByte);
    }
    refBases = ArrayUtils.addAll(refBases, ArrayUtils.subarray(nextVC.getReference().getBases(),
            locus > nextStart ? 1 : 0, nextVC.getReference().getBases().length)); // special case of deletion including the padding base of consecutive indel
    altBases = ArrayUtils.addAll(altBases, nextVC.getAlternateAllele(0).getBases());

    int iii = 0;
    if (refBases.length == altBases.length) { // insertion + deletion of same length creates an MNP --> trim common prefix bases off the beginning of the allele
        while (iii < refBases.length && refBases[iii] == altBases[iii]) {
            iii++;
        }
        if (iii == refBases.length) {
            // we've become a null allele, such as with CA/C + A/AA -> CA/CA => after trimming there's nothing left
            // so return a null variant context so we can eliminate the variants from consideration
            return null;
        }
    }

    final Allele refAllele = Allele.create(ArrayUtils.subarray(refBases, iii, refBases.length), true);
    final Allele altAllele = Allele.create(ArrayUtils.subarray(altBases, iii, altBases.length), false);
    return new VariantContextBuilder("merged", thisVC.getChr(), thisVC.getStart() + iii, nextVC.getEnd(),
            Arrays.asList(refAllele, altAllele)).make();
}

From source file:org.broadinstitute.gatk.utils.haplotype.EventMap.java

protected void processCigarForInitialEvents() {
    final Cigar cigar = haplotype.getCigar();
    final byte[] alignment = haplotype.getBases();

    int refPos = haplotype.getAlignmentStartHapwrtRef();
    if (refPos < 0) {
        return;/*from   w  w  w.j  ava2s . c  o m*/
    } // Protection against SW failures

    final List<VariantContext> proposedEvents = new ArrayList<>();

    int alignmentPos = 0;

    for (int cigarIndex = 0; cigarIndex < cigar.numCigarElements(); cigarIndex++) {
        final CigarElement ce = cigar.getCigarElement(cigarIndex);
        final int elementLength = ce.getLength();
        switch (ce.getOperator()) {
        case I: {
            if (refPos > 0) { // protect against trying to create insertions/deletions at the beginning of a contig
                final List<Allele> insertionAlleles = new ArrayList<Allele>();
                final int insertionStart = refLoc.getStart() + refPos - 1;
                final byte refByte = ref[refPos - 1];
                if (BaseUtils.isRegularBase(refByte)) {
                    insertionAlleles.add(Allele.create(refByte, true));
                }
                if (cigarIndex == 0 || cigarIndex == cigar.getCigarElements().size() - 1) {
                    // if the insertion isn't completely resolved in the haplotype, skip it
                    // note this used to emit SYMBOLIC_UNASSEMBLED_EVENT_ALLELE but that seems dangerous
                } else {
                    byte[] insertionBases = new byte[] {};
                    insertionBases = ArrayUtils.add(insertionBases, ref[refPos - 1]); // add the padding base
                    insertionBases = ArrayUtils.addAll(insertionBases,
                            Arrays.copyOfRange(alignment, alignmentPos, alignmentPos + elementLength));
                    if (BaseUtils.isAllRegularBases(insertionBases)) {
                        insertionAlleles.add(Allele.create(insertionBases, false));
                    }
                }
                if (insertionAlleles.size() == 2) { // found a proper ref and alt allele
                    proposedEvents.add(new VariantContextBuilder(sourceNameToAdd, refLoc.getContig(),
                            insertionStart, insertionStart, insertionAlleles).make());
                }
            }
            alignmentPos += elementLength;
            break;
        }
        case S: {
            alignmentPos += elementLength;
            break;
        }
        case D: {
            if (refPos > 0) { // protect against trying to create insertions/deletions at the beginning of a contig
                final byte[] deletionBases = Arrays.copyOfRange(ref, refPos - 1, refPos + elementLength); // add padding base
                final List<Allele> deletionAlleles = new ArrayList<Allele>();
                final int deletionStart = refLoc.getStart() + refPos - 1;
                final byte refByte = ref[refPos - 1];
                if (BaseUtils.isRegularBase(refByte) && BaseUtils.isAllRegularBases(deletionBases)) {
                    deletionAlleles.add(Allele.create(deletionBases, true));
                    deletionAlleles.add(Allele.create(refByte, false));
                    proposedEvents.add(new VariantContextBuilder(sourceNameToAdd, refLoc.getContig(),
                            deletionStart, deletionStart + elementLength, deletionAlleles).make());
                }
            }
            refPos += elementLength;
            break;
        }
        case M:
        case EQ:
        case X: {
            for (int iii = 0; iii < elementLength; iii++) {
                final byte refByte = ref[refPos];
                final byte altByte = alignment[alignmentPos];
                if (refByte != altByte) { // SNP!
                    if (BaseUtils.isRegularBase(refByte) && BaseUtils.isRegularBase(altByte)) {
                        final List<Allele> snpAlleles = new ArrayList<Allele>();
                        snpAlleles.add(Allele.create(refByte, true));
                        snpAlleles.add(Allele.create(altByte, false));
                        proposedEvents.add(new VariantContextBuilder(sourceNameToAdd, refLoc.getContig(),
                                refLoc.getStart() + refPos, refLoc.getStart() + refPos, snpAlleles).make());
                    }
                }
                refPos++;
                alignmentPos++;
            }
            break;
        }
        case N:
        case H:
        case P:
        default:
            throw new ReviewedGATKException(
                    "Unsupported cigar operator created during SW alignment: " + ce.getOperator());
        }
    }

    for (final VariantContext proposedEvent : proposedEvents)
        addVC(proposedEvent, true);
}

From source file:org.broadinstitute.sting.utils.haplotype.EventMap.java

protected void processCigarForInitialEvents() {
    final Cigar cigar = haplotype.getCigar();
    final byte[] alignment = haplotype.getBases();

    int refPos = haplotype.getAlignmentStartHapwrtRef();
    if (refPos < 0) {
        return;/*from w w  w .j a va2s.  c  o m*/
    } // Protection against SW failures

    int alignmentPos = 0;

    for (int cigarIndex = 0; cigarIndex < cigar.numCigarElements(); cigarIndex++) {
        final CigarElement ce = cigar.getCigarElement(cigarIndex);
        final int elementLength = ce.getLength();
        switch (ce.getOperator()) {
        case I: {
            if (refPos > 0) { // protect against trying to create insertions/deletions at the beginning of a contig
                final List<Allele> insertionAlleles = new ArrayList<Allele>();
                final int insertionStart = refLoc.getStart() + refPos - 1;
                final byte refByte = ref[refPos - 1];
                if (BaseUtils.isRegularBase(refByte)) {
                    insertionAlleles.add(Allele.create(refByte, true));
                }
                if (cigarIndex == 0 || cigarIndex == cigar.getCigarElements().size() - 1) {
                    // if the insertion isn't completely resolved in the haplotype, skip it
                    // note this used to emit SYMBOLIC_UNASSEMBLED_EVENT_ALLELE but that seems dangerous
                } else {
                    byte[] insertionBases = new byte[] {};
                    insertionBases = ArrayUtils.add(insertionBases, ref[refPos - 1]); // add the padding base
                    insertionBases = ArrayUtils.addAll(insertionBases,
                            Arrays.copyOfRange(alignment, alignmentPos, alignmentPos + elementLength));
                    if (BaseUtils.isAllRegularBases(insertionBases)) {
                        insertionAlleles.add(Allele.create(insertionBases, false));
                    }
                }
                if (insertionAlleles.size() == 2) { // found a proper ref and alt allele
                    addVC(new VariantContextBuilder(sourceNameToAdd, refLoc.getContig(), insertionStart,
                            insertionStart, insertionAlleles).make());
                }
            }
            alignmentPos += elementLength;
            break;
        }
        case S: {
            alignmentPos += elementLength;
            break;
        }
        case D: {
            if (refPos > 0) { // protect against trying to create insertions/deletions at the beginning of a contig
                final byte[] deletionBases = Arrays.copyOfRange(ref, refPos - 1, refPos + elementLength); // add padding base
                final List<Allele> deletionAlleles = new ArrayList<Allele>();
                final int deletionStart = refLoc.getStart() + refPos - 1;
                final byte refByte = ref[refPos - 1];
                if (BaseUtils.isRegularBase(refByte) && BaseUtils.isAllRegularBases(deletionBases)) {
                    deletionAlleles.add(Allele.create(deletionBases, true));
                    deletionAlleles.add(Allele.create(refByte, false));
                    addVC(new VariantContextBuilder(sourceNameToAdd, refLoc.getContig(), deletionStart,
                            deletionStart + elementLength, deletionAlleles).make());
                }
            }
            refPos += elementLength;
            break;
        }
        case M:
        case EQ:
        case X: {
            for (int iii = 0; iii < elementLength; iii++) {
                final byte refByte = ref[refPos];
                final byte altByte = alignment[alignmentPos];
                if (refByte != altByte) { // SNP!
                    if (BaseUtils.isRegularBase(refByte) && BaseUtils.isRegularBase(altByte)) {
                        final List<Allele> snpAlleles = new ArrayList<Allele>();
                        snpAlleles.add(Allele.create(refByte, true));
                        snpAlleles.add(Allele.create(altByte, false));
                        addVC(new VariantContextBuilder(sourceNameToAdd, refLoc.getContig(),
                                refLoc.getStart() + refPos, refLoc.getStart() + refPos, snpAlleles).make());
                    }
                }
                refPos++;
                alignmentPos++;
            }
            break;
        }
        case N:
        case H:
        case P:
        default:
            throw new ReviewedStingException(
                    "Unsupported cigar operator created during SW alignment: " + ce.getOperator());
        }
    }
}

From source file:org.broadleafcommerce.common.cache.AbstractCacheMissAware.java

/**
 * Retrieve a null representation of the cache item. This representation is the same for
 * all cache misses and is used as the object representation to store in the cache for a
 * cache miss.//from   w  ww .  ja va 2  s. c  o  m
 *
 * @param responseClass the class representing the type of the cache item
 * @param <T> the type of the cache item
 * @return the null representation for the cache item
 */
protected synchronized <T> T getNullObject(final Class<T> responseClass) {
    if (nullObject == null) {
        Class<?>[] interfaces = (Class<?>[]) ArrayUtils.add(ClassUtils.getAllInterfacesForClass(responseClass),
                Serializable.class);
        nullObject = Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                if (method.getName().equals("equals")) {
                    return !(objects[0] == null) && objects[0].hashCode() == 31;
                } else if (method.getName().equals("hashCode")) {
                    return 31;
                } else if (method.getName().equals("toString")) {
                    return "Null_" + responseClass.getSimpleName();
                }
                throw new IllegalAccessException("Not a real object");
            }
        });
    }
    return (T) nullObject;
}

From source file:org.broadleafcommerce.core.web.processor.ToggleFacetLinkProcessor.java

@Override
@SuppressWarnings("unchecked")
protected Map<String, String> getModifiedAttributeValues(Arguments arguments, Element element,
        String attributeName) {/*from   w w w. j ava  2 s. c o m*/
    Map<String, String> attrs = new HashMap<String, String>();

    BroadleafRequestContext blcContext = BroadleafRequestContext.getBroadleafRequestContext();
    HttpServletRequest request = blcContext.getRequest();

    String baseUrl = request.getRequestURL().toString();
    Map<String, String[]> params = new HashMap<String, String[]>(request.getParameterMap());

    Expression expression = (Expression) StandardExpressions.getExpressionParser(arguments.getConfiguration())
            .parseExpression(arguments.getConfiguration(), arguments, element.getAttributeValue(attributeName));
    SearchFacetResultDTO result = (SearchFacetResultDTO) expression.execute(arguments.getConfiguration(),
            arguments);

    String key = facetService.getUrlKey(result);
    String value = facetService.getValue(result);
    String[] paramValues = params.get(key);

    if (ArrayUtils.contains(paramValues, facetService.getValue(result))) {
        paramValues = (String[]) ArrayUtils.removeElement(paramValues, facetService.getValue(result));
    } else {
        paramValues = (String[]) ArrayUtils.add(paramValues, value);
    }

    params.remove(SearchCriteria.PAGE_NUMBER);
    params.put(key, paramValues);

    String url = ProcessorUtils.getUrl(baseUrl, params);

    attrs.put("href", url);
    return attrs;
}

From source file:org.broadleafcommerce.openadmin.server.dao.DynamicEntityDaoImpl.java

protected void addClassToTree(Class<?> clazz, ClassTree tree) {
    Class<?> testClass;/*from   w ww  . j  a v  a2  s  . co  m*/
    try {
        testClass = Class.forName(tree.getFullyQualifiedClassname());
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
    if (clazz.equals(testClass)) {
        return;
    }
    if (clazz.getSuperclass().equals(testClass)) {
        ClassTree myTree = new ClassTree(clazz.getName(), isExcludeClassFromPolymorphism(clazz));
        createClassTreeFromAnnotation(clazz, myTree);
        tree.setChildren((ClassTree[]) ArrayUtils.add(tree.getChildren(), myTree));
    } else {
        for (ClassTree child : tree.getChildren()) {
            addClassToTree(clazz, child);
        }
    }
}