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:com.ikanow.infinit.e.data_model.store.document.DocumentPojo.java

public void addToMetadata(String fieldName, Object fieldVal) {
    if (null == metadata) {
        metadata = new LinkedHashMap<String, Object[]>();
    }//from  w ww  . ja va  2  s  .  c om
    Object obj[] = new Object[1];
    obj[0] = fieldVal;
    Object[] current = metadata.get(fieldName);
    if (null != current) {
        metadata.put(fieldName, ArrayUtils.add(current, obj));
    } else {
        metadata.put(fieldName, obj);
    }
}

From source file:fr.inria.atlanmod.neoemf.datastore.estores.impl.DirectWriteHbaseResourceEStoreImpl.java

protected void add(NeoEMFEObject object, EAttribute eAttribute, int index, Object value) {
    try {/*from ww w . ja v a 2s .  com*/
        String[] array;
        boolean passed = false;
        int attemp = 0;

        do {
            array = (String[]) getFromTable(object, eAttribute);
            //array = (String[]) ArrayUtils.add(array, index, serializeValue(eAttribute, value));
            Put put = new Put(Bytes.toBytes(object.neoemfId()))
                    .add(PROPERTY_FAMILY, Bytes.toBytes(eAttribute.getName()),
                            NeoEMFUtil.EncoderUtil.toBytes(index < 0
                                    ? (String[]) ArrayUtils.add(array, serializeValue(eAttribute, value))
                                    : (String[]) ArrayUtils.add(array, serializeValue(eAttribute, value))));
            passed = table.checkAndPut(Bytes.toBytes(object.neoemfId()), PROPERTY_FAMILY,
                    Bytes.toBytes(eAttribute.getName()),
                    array == null ? null : NeoEMFUtil.EncoderUtil.toBytes(array), put);
            if (!passed) {
                if (attemp > ATTEMP_TIMES_DEFAULT)
                    throw new TimeoutException();
                Thread.sleep((++attemp) * SLEEP_DEFAULT);
            }

        } while (!passed);

    } catch (IOException e) {
        Logger.log(Logger.SEVERITY_ERROR, MessageFormat.format(
                "Unable to add ''{0}'' to ''{1}'' for element ''{2}''", value, eAttribute.getName(), object));
    } catch (TimeoutException e) {
        Logger.log(Logger.SEVERITY_ERROR,
                MessageFormat.format("Unable to add ''{0}'' to ''{1}'' for element ''{2}'' after ''{3}'' times",
                        value, eAttribute.getName(), object, ATTEMP_TIMES_DEFAULT));
        e.printStackTrace();
    } catch (InterruptedException e) {
        Logger.log(Logger.SEVERITY_ERROR, MessageFormat
                .format("InterruptedException while updating element ''{0}''.\n{1}", object, e.getMessage()));
        e.printStackTrace();
    }
}

From source file:gda.scan.ScanDataPoint.java

/**
 * Add a detector to the list of detectors this object holds data from. This stores the name in the detectorHeader
 * array and detectorNames array. If its a countertimer is stored in the boolean array. The contents of the
 * detectorHeader and detectorNames arrays will be different if the detector is a countertimer.
 * <p>/*from  w ww  . j  a va  2s.co  m*/
 * Note this does not readout the detector! Data must be added by using the addData method.
 * 
 * @param det
 */
@Override
public void addDetector(Detector det) {
    //      detectorNames = (String[]) ArrayUtils.add(detectorNames, det.getName());
    scanInfo.setDetectorNames((String[]) ArrayUtils.add(scanInfo.getDetectorNames(), det.getName()));
    String[] extraNames = det.getExtraNames();
    if (extraNames != null && extraNames.length > 0) {
        detectorHeader = (String[]) ArrayUtils.addAll(detectorHeader, extraNames);
    } else {
        detectorHeader = (String[]) ArrayUtils.add(detectorHeader, det.getName());
    }
    detectors.add(det);
}

From source file:gda.device.scannable.scannablegroup.ScannableGroup.java

@Override
public String toFormattedString() {
    //TODO this method does not provide correct indentation level for a scannable group inside another scannable group
    //TODO the regex parser is unreliable as described by FIXME below
    // IT would be better to create format message by delegate to individual members directly, rather than re-parsing output again.

    //TODO this works if the toFormattedString method of the members conforms to a standard. But I don't think there is one!
    //Rather use getPosition and format here.
    String membersOutput = getName() + " ::\n";
    for (Scannable member : groupMembers) {
        membersOutput += member.toFormattedString() + "\n";
    }//from ww w  . j a va2 s. c  o  m

    String[] originalInputNames = getInputNames();
    String[] namesToSplitOn = getInputNames();
    String[] names = getGroupMemberNames();
    String[] extras = getExtraNames();

    // FIXME regex-based splitting of membersOutput is broken if one group member name is a substring of another - e.g. "col_y" and "col_yaw"

    if (originalInputNames.length + extras.length == 0) {
        return membersOutput;
    }

    if (extras.length > 0) {
        namesToSplitOn = (String[]) ArrayUtils.addAll(namesToSplitOn, extras);
    }

    // find the longest name, to help with formatting the output
    int longestName = 0;
    for (String objName : namesToSplitOn) {
        if (objName.length() > longestName) {
            longestName = objName.length();
        }
    }
    namesToSplitOn = (String[]) ArrayUtils.add(namesToSplitOn, getName());
    namesToSplitOn = (String[]) ArrayUtils.addAll(namesToSplitOn, names);

    String regex = "";
    for (String name : namesToSplitOn) {
        regex += name + " +|";
    }
    regex = regex.substring(0, regex.length() - 1);

    String[] values = membersOutput.split(regex);

    String returnString = getName() + "::\n";
    int nextNameIndex = 0;
    for (int i = 0; i < values.length; i++) {
        String value = values[i].trim();
        if (value.startsWith(":")) {
            value = value.substring(1).trim();
        }
        if (StringUtils.containsOnly(value, ":()") || value.isEmpty()) {
            continue;
        }
        returnString += " " + StringUtils.rightPad(namesToSplitOn[nextNameIndex], longestName) + ": " + value
                + "\n";
        nextNameIndex++;
    }
    returnString.trim();
    returnString = returnString.substring(0, returnString.length() - 1);

    return returnString;
}

From source file:gda.scan.ScanDataPoint.java

/**
 * Add a scannable to the list of scannables this object holds data on.
 * <p>//  www .j a v  a2  s  . c o  m
 * Note that this does not read the current position of the scannable.
 * 
 * @param scannable
 */
@Override
public void addScannable(Scannable scannable) {
    //      scannableNames = (String[]) ArrayUtils.add(scannableNames, scannable.getName());
    scanInfo.setScannableNames((String[]) ArrayUtils.add(scanInfo.getScannableNames(), scannable.getName()));
    scannableHeader = (String[]) ArrayUtils.addAll(scannableHeader, scannable.getInputNames());
    scannableHeader = (String[]) ArrayUtils.addAll(scannableHeader, scannable.getExtraNames());
    scannables.add(scannable);
}

From source file:com.siberhus.tdfl.DataFileLoader.java

/**
 * /*from w w w .j a  va 2 s .com*/
 * @param dataContext
 * @param reader
 * @param successWriter
 * @param errorWriter
 * @throws Exception
 */
private void _doReadProcessWrite(DataContext dataContext, DataFileReader reader, DataFileWriter successWriter,
        DataFileWriter errorWriter) throws Exception {

    boolean successLabeled = false, errorLabeled = false;

    reader.open(dataContext);

    String labels[] = null, values[] = null;
    if (reader.isReadLabels()) {
        labels = reader.read();
    }

    int successCount = 0, lineCount = 0;
    while ((values = reader.read()) != null) {
        lineCount++;
        dataContext.linesRead += reader.getLinesRead();
        FieldSet fieldSet = null;
        if (labels != null) {
            if (values.length > labels.length) {
                List<String> vList = new ArrayList<String>();
                for (int i = 0; i < labels.length; i++) {
                    vList.add(values[i]);
                }
                values = vList.toArray(new String[0]);
            }
            fieldSet = new DefaultFieldSet(values, labels);
        } else {
            fieldSet = new DefaultFieldSet(values);
        }

        FieldDataException fde = new FieldDataException();
        T item = null;
        try {
            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException("Current thread is interrupted");
            }
            item = dataFileProcessor.mapLine(fieldSet, fde);
            if (item == null) {
                //skip
                continue;
            }
            dataFileProcessor.validateItem(item, fde);
            if (fde.hasErrors()) {
                if (fde.isForceProcess()) {
                    dataFileProcessor.processItem(item);
                }
                throw fde;
            }
            dataFileProcessor.processItem(item);
            successCount++;
            if (successCount == updateInterval) {
                successCount = 0;//reset
                dataFileProcessor.update();
                reader.update(dataContext);
                if (successWriter != null)
                    successWriter.update(dataContext);
                if (errorWriter != null)
                    errorWriter.update(dataContext);
                //TODO: save dataContext here
            }
            dataContext.itemSuccessCount++;
            dataFileProcessor.onItemSuccess(item);
            if (!successLabeled && labels != null) {
                lazyOpenWriterThenWriteLabels(dataContext, successWriter, labels);
                successLabeled = true;
            }
            lazyOpenWriterThenWrite(dataContext, successWriter, values);
            if (successWriter != null)
                dataContext.successLinesWritten += successWriter.getLinesWritten();
        } catch (InterruptedException e) {
            logger.info("Data processing is interrupted on file " + dataContext.getResource().getFilename());
            dataFileProcessor.onInterrupt(e);
            throw new DataFileLoaderException(e);
        } catch (Exception e) {
            if (!(e instanceof FieldDataException)) {
                if (e instanceof CancelException) {
                    logger.info(
                            "Data processing is cancelled on file " + dataContext.getResource().getFilename());
                    dataFileProcessor.onCancel((CancelException) e);
                    //                  break;
                    throw e;
                }
                logger.error(e.getMessage(), e);
            }
            dataContext.itemErrorCount++;
            dataFileProcessor.onItemError(item, e);

            if (!errorLabeled && labels != null) {
                lazyOpenWriterThenWriteLabels(dataContext, errorWriter, labels);
                errorLabeled = true;
            }
            String valuesWithErr[] = (String[]) ArrayUtils.add(values, e.toString());
            lazyOpenWriterThenWrite(dataContext, errorWriter, valuesWithErr);
            if (errorWriter != null)
                dataContext.errorLinesWritten += errorWriter.getLinesWritten();
        } finally {
            if (lineCount > 0) {
                //do again in case there are no success item.
                dataFileProcessor.update();
                reader.update(dataContext);
                if (successWriter != null)
                    successWriter.update(dataContext);
                if (errorWriter != null)
                    errorWriter.update(dataContext);
                //TODO: save dataContext here
            }
        }
    } //end while
}

From source file:gda.jython.translator.GeneralTranslator.java

public static String[] splitGroup(String during) {
    String[] output = new String[0];
    StringBuffer buf = new StringBuffer();
    int index = 0;
    String[] quoteTypes = new String[] { "'''", "r\"", "r\'", "\'", "\"" }; //put most complex first
    while (index < during.length()) {
        if (during.regionMatches(index, " ", 0, 1) || during.regionMatches(index, ",", 0, 1)) {
            if (buf.length() > 0) {
                output = (String[]) ArrayUtils.add(output, buf.toString());
                buf = new StringBuffer();
            }//from   w w  w.ja  v a  2  s.  c  om
            index++;
            continue;
        }
        boolean quoteTypeFound = false;
        for (String quoteType : quoteTypes) {
            if (during.regionMatches(index, quoteType, 0, quoteType.length())) {
                if (buf.length() > 0) {
                    output = (String[]) ArrayUtils.add(output, buf.toString());
                    buf = new StringBuffer();
                }
                buf.append(quoteType);
                index += quoteType.length();
                //start of quote so go up to the matching quote - allowing for escaped versions
                String endQuote = quoteType;
                if (endQuote == "r\"")
                    endQuote = "\"";
                if (endQuote == "r\'")
                    endQuote = "\'";
                while (index < during.length()) {
                    if (during.regionMatches(index, endQuote, 0, endQuote.length())) {
                        buf.append(endQuote);
                        index += endQuote.length();
                        output = (String[]) ArrayUtils.add(output, buf.toString());
                        buf = new StringBuffer();
                        break;
                    }
                    char charAt = during.charAt(index);
                    buf.append(during.charAt(index));
                    index++;
                    if (charAt == '\\') {
                        if (index < during.length()) {
                            buf.append(during.charAt(index));
                            index++;
                        }
                    }
                }
                if (buf.length() > 0) {
                    output = (String[]) ArrayUtils.add(output, buf.toString());
                    buf = new StringBuffer();
                }
                quoteTypeFound = true;
                break;
            }
        }
        if (quoteTypeFound)
            continue;
        //add to StringBuffer
        char charAt = during.charAt(index);
        buf.append(charAt);
        index++;
        if (charAt == '\\') {
            if (index < during.length()) {
                buf.append(during.charAt(index));
                index++;
            }
        }
    }
    if (buf.length() > 0) {
        output = (String[]) ArrayUtils.add(output, buf.toString());
        buf = new StringBuffer();
    }
    //at end move over buf contents
    return output;
}

From source file:com.novartis.opensource.yada.test.ServiceTest.java

/**
 * Creates a {@link com.novartis.opensource.yada.YADARequest} object and
 * populates it with values in {@code query}
 * /*from w  w  w.  j a  v a2 s.  co m*/
 * @param query the query to use in the request
 * @return a {@link com.novartis.opensource.yada.YADARequest} object
 * @throws YADAQueryConfigurationException when request creation fails
 */
public YADARequest getYADAReq(String query) throws YADAQueryConfigurationException {

    logQuery(query);
    YADARequest yadaReq = new YADARequest();
    yadaReq.setUpdateStats(new String[] { "false" });
    String[] array = query.split(AMP);
    Map<String, String[]> paraMap = new HashMap<>();
    for (String param : array) {
        String[] pair = param.split(EQUAL);
        String[] vals = paraMap.get(pair[0]);
        if (vals == null) {
            paraMap.put(pair[0], new String[] { pair[1] });
        } else {
            paraMap.put(pair[0], (String[]) ArrayUtils.add(vals, pair[1]));
        }
    }
    for (String key : paraMap.keySet()) {
        String[] val = paraMap.get(key);//null;
        if (key.equals(YADARequest.PL_JSONPARAMS) || key.equals(YADARequest.PS_JSONPARAMS) && val != null)
            yadaReq.setJsonParams(new JSONParams(new JSONArray(val[0])));
        else {
            try {
                if (val != null)
                    yadaReq.invokeSetter(key, val);
            } catch (YADARequestException e) {
                throw new YADAQueryConfigurationException("Problem invoking setter.", e);
            }
        }
    }
    return yadaReq;
}

From source file:com.flexive.core.security.UserTicketImpl.java

/**
 * Helper function for the constructor.// ww  w  .j a v  a2 s .c  o  m
 */
private void populateData() {

    this.dirty = false;
    this.creationTime = System.currentTimeMillis();
    this.remoteHost = FxContext.get().getRemoteHost();

    // Check ACL assignments
    if (assignments == null) {
        assignments = new ACLAssignment[0];
    }

    // Check groups
    if (this.groups == null || this.groups.length == 0) {
        this.groups = new long[] { UserGroup.GROUP_EVERYONE };
    } else {
        // Group everyone has to be present
        if (!(ArrayUtils.contains(this.groups, UserGroup.GROUP_EVERYONE))) {
            this.groups = ArrayUtils.add(this.groups, UserGroup.GROUP_EVERYONE);
        }
    }

    // Check roles
    if (this.roles == null) {
        this.roles = new Role[0];
    }

    // Set mandator/global supervisor flag
    if (this.userId == Account.USER_GLOBAL_SUPERVISOR || isInRole(Role.GlobalSupervisor)) {
        globalSupervisor = true;
    }
    if (isInRole(Role.MandatorSupervisor)) {
        mandatorSupervisor = true;
    }
}

From source file:au.org.ala.biocache.dao.SearchDAOImpl.java

/**
 * (Endemic)//from www .j a v a 2 s .  c  o  m
 *
 * Returns a list of species that are only within a subQuery.
 *
 * The subQuery is a subset of parentQuery.
 */
public List<FieldResultDTO> getSubquerySpeciesOnly(SpatialSearchRequestParams subQuery,
        SpatialSearchRequestParams parentQuery) throws Exception {
    if (executor == null) {
        executor = Executors.newFixedThreadPool(maxMultiPartThreads);
    }
    // 1)get a list of species that are in the WKT
    logger.debug("Starting to get Endemic Species...");
    subQuery.setFacet(true);
    subQuery.setFacets(parentQuery.getFacets());
    List<FieldResultDTO> list1 = getValuesForFacet(subQuery);
    logger.debug("Retrieved species within area...(" + list1.size() + ")");

    int i = 0, localterms = 0;

    String facet = parentQuery.getFacets()[0];
    String[] originalFqs = parentQuery.getFq();
    List<Future<List<FieldResultDTO>>> threads = new ArrayList<Future<List<FieldResultDTO>>>();
    //batch up the rest of the world query so that we have fqs based on species we want to test for. This should improve the performance of the endemic services.
    while (i < list1.size()) {
        StringBuffer sb = new StringBuffer();
        while ((localterms == 0 || localterms % termQueryLimit != 0) && i < list1.size()) {
            if (localterms != 0)
                sb.append(" OR ");
            String value = list1.get(i).getFieldValue();
            if (facet.equals(NAMES_AND_LSID)) {
                if (value.startsWith("\"") && value.endsWith("\"")) {
                    value = value.substring(1, value.length() - 1);
                }
                value = "\"" + ClientUtils.escapeQueryChars(value) + "\"";
            } else {
                value = ClientUtils.escapeQueryChars(value);
            }
            sb.append(facet).append(":").append(value);
            i++;
            localterms++;
        }
        String newfq = sb.toString();
        if (localterms == 1)
            newfq = newfq + " OR " + newfq; //cater for the situation where there is only one term.  We don't want the term to be escaped again
        localterms = 0;
        SpatialSearchRequestParams srp = new SpatialSearchRequestParams();
        BeanUtils.copyProperties(parentQuery, srp);
        srp.setFq((String[]) ArrayUtils.add(originalFqs, newfq));
        int batch = i / termQueryLimit;
        EndemicCallable callable = new EndemicCallable(srp, batch, this);
        threads.add(executor.submit(callable));
    }

    Collections.sort(list1);
    for (Future<List<FieldResultDTO>> future : threads) {
        List<FieldResultDTO> list = future.get();
        if (list != null) {
            for (FieldResultDTO find : list) {
                int idx = Collections.binarySearch(list1, find);
                //remove if subquery count < parentquery count
                if (idx >= 0 && list1.get(idx).getCount() < find.getCount()) {
                    list1.remove(idx);
                }
            }
        }
    }
    logger.debug("Determined final endemic list (" + list1.size() + ")...");
    return list1;
}