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

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

Introduction

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

Prototype

public static double[] addAll(double[] array1, double[] array2) 

Source Link

Document

Adds all the elements of the given arrays into a new array.

Usage

From source file:com.bayesforecast.ingdat.vigsteps.vigmake.VigMakeStep.java

public void emitItem(VigMakeStepData data, Item item, boolean emitLastState) {
    Set<Date> processedDates = data.processedDates.keySet();
    Object[] ids = item.getId().toArray();
    Object[] attributes = item.getAttributes().toArray();
    Object[] itemData = ArrayUtils.addAll(ids, attributes);
    Set<Entry<Date, State>> set = item.getStates().entrySet();
    for (Entry<Date, State> status : set) {
        if (!status.getValue().isNullState()
                && !(item.getStates().lastKey().equals(status.getKey()) && !emitLastState)) {
            Object[] itemStateData = ArrayUtils.addAll(itemData, status.getValue().getStatus().toArray());
            Object[] itemStateData2 = ArrayUtils.add(itemStateData, status.getKey());
            Date dateEnd = null;//from w w  w  .  j ava 2s .co  m
            Object[] statusPrev = new Object[meta.getStatusFields().size()];
            Object[] statusNext = new Object[meta.getStatusFields().size()];
            if (status.getValue().getPrevious() != null && !status.getValue().getPrevious().isNullState()) {
                statusPrev = status.getValue().getPrevious().getStatus().toArray();
            }
            if (status.getValue().getNext() != null) {
                if (!status.getValue().getNext().isNullState()) {
                    statusNext = status.getValue().getNext().getStatus().toArray();
                    dateEnd = item.getStates().higherKey(status.getKey());
                } else {
                    dateEnd = DateUtils.addDays(item.getStates().higherKey(status.getKey()), -1);
                }
            }
            Object[] itemStateData3 = ArrayUtils.add(itemStateData2, dateEnd);
            Object[] itemStateData4 = ArrayUtils.addAll(itemStateData3, statusPrev);
            Object[] itemStateData5 = ArrayUtils.addAll(itemStateData4, statusNext);

            // put the row to the output row stream
            try {
                putRow(data.outputRowMeta, itemStateData5);
            } catch (KettleStepException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:edu.utdallas.bigsecret.crypter.CrypterMode1.java

/**
 * {@inheritDoc}//  w w  w  .j  ava2 s . c  o m
 */
public byte[] wrapQualifier(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value)
        throws Exception {
    if (row == null || row.length == 0)
        throw new Exception("Row is null or has no data");
    else if (family == null || family.length == 0)
        throw new Exception("Family is null or has no data");
    else if (qualifier == null || qualifier.length == 0)
        throw new Exception("Qualifier is null or has no data");

    byte[] qualifierIndex = getIndexQualifierData(qualifier);

    byte[] sizeArray = Bytes.toBytes(row.length);
    sizeArray = ArrayUtils.addAll(sizeArray, Bytes.toBytes(family.length));
    sizeArray = ArrayUtils.addAll(sizeArray, Bytes.toBytes(qualifier.length));

    byte[] completeData = ArrayUtils.addAll(sizeArray, row);
    completeData = ArrayUtils.addAll(completeData, family);
    completeData = ArrayUtils.addAll(completeData, qualifier);
    completeData = ArrayUtils.addAll(completeData, Bytes.toBytes(ts));

    completeData = m_keyCipher.encrypt(completeData);

    return ArrayUtils.addAll(qualifierIndex, completeData);
}

From source file:marytts.unitselection.analysis.ProsodyAnalyzer.java

public double[] getF0Factors() {
    double[] f0Factors = null;
    for (Phone phone : phones) {
        double[] phoneF0Factors = phone.getF0Factors();
        f0Factors = ArrayUtils.addAll(f0Factors, phoneF0Factors);
    }/* w  ww . j  av  a  2s.  c om*/
    return f0Factors;
}

From source file:ml.shifu.shifu.container.meta.MetaFactory.java

/**
 * Iterate each property of Object, get the value and validate
 * //from  w w  w  .j  a  va2 s . c  o  m
 * @param isGridSearch
 *            - if grid search, ignore validation in train#params as they are set all as list
 * @param ptag
 *            - the prefix of key to search @MetaItem
 * @param obj
 *            - the object to validate
 * @return ValidateResult
 *         If all items are OK, the ValidateResult.status will be true;
 *         Or the ValidateResult.status will be false, ValidateResult.causes will contain the reasons
 * @throws Exception
 *             any exception in validaiton
 */
public static ValidateResult iterateCheck(boolean isGridSearch, String ptag, Object obj) throws Exception {
    ValidateResult result = new ValidateResult(true);
    if (obj == null) {
        return result;
    }

    Class<?> cls = obj.getClass();
    Field[] fields = cls.getDeclaredFields();

    Class<?> parentCls = cls.getSuperclass();
    if (!parentCls.equals(Object.class)) {
        Field[] pfs = parentCls.getDeclaredFields();
        fields = (Field[]) ArrayUtils.addAll(fields, pfs);
    }

    for (Field field : fields) {
        if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !isJsonIngoreField(field)) {
            Method method = cls.getMethod("get" + getMethodName(field.getName()));
            Object value = method.invoke(obj);

            encapsulateResult(result,
                    validate(isGridSearch, ptag + ITEM_KEY_SEPERATOR + field.getName(), value));
        }
    }

    return result;
}

From source file:com.bah.bahdit.main.plugins.imageindex.ImageIndex.java

/**
 * Gets tags from the query and returns the hashes
 * associated with those tags./*from   ww w.  j  ava  2 s .  c o  m*/
 * 
 * @param tagScanner - batch scanner to the tag table
 * @param query - the query specified by the user
 * @return - hashes found that satisfy the query
 */
private HashSet<String> getTag(BatchScanner tagScanner, String query) {

    List<Range> ranges = new ArrayList<Range>();
    for (String s : query.split(" ")) {
        ranges.add(new Range(s));
    }
    tagScanner.setRanges(ranges);

    HashSet<String> hashRanges = new HashSet<String>();
    for (Entry<Key, Value> e : tagScanner) {
        hashRanges.add(new String(e.getValue().get()));
    }

    if (hashRanges.size() == 0) {
        String[] suggestions = { query };
        try {
            for (String q : query.split("\\s")) {
                suggestions = (String[]) ArrayUtils.addAll(suggestions, tagSpellChecker.suggestSimilar(q, 1));
            }
        } catch (IOException e) {
            log.warn(e.getMessage());
        }
        for (Entry<Key, Value> e : tagScanner) {
            hashRanges.add(new String(e.getValue().get()));
        }
        if (hashRanges.size() == 0)
            return null;
    }

    return hashRanges;
}

From source file:ips1ap101.lib.core.jsf.JSF.java

public static CampoArchivoMultiPart upload(Part part, String carpeta, EnumOpcionUpload opcion)
        throws Exception {
    Bitacora.trace(JSF.class, "upload", part, carpeta, opcion);
    if (part == null) {
        return null;
    }//from ww  w.j  a va 2  s  . c  o  m
    if (part.getSize() == 0) {
        return null;
    }
    String originalName = getPartFileName(part);
    if (StringUtils.isBlank(originalName)) {
        return null;
    }
    CampoArchivoMultiPart campoArchivo = new CampoArchivoMultiPart();
    campoArchivo.setPart(part);
    campoArchivo.setClientFileName(null);
    campoArchivo.setServerFileName(null);
    /**/
    Bitacora.trace(JSF.class, "upload", "name=" + part.getName());
    Bitacora.trace(JSF.class, "upload", "type=" + part.getContentType());
    Bitacora.trace(JSF.class, "upload", "size=" + part.getSize());
    /**/
    String sep = System.getProperties().getProperty("file.separator");
    String validChars = StrUtils.VALID_CHARS;
    String filepath = null;
    if (STP.esIdentificadorArchivoValido(carpeta)) {
        filepath = carpeta.replace(".", sep);
    }
    long id = LongUtils.getNewId();
    //      String filename = STP.getRandomString();
    String filename = id + "";
    String pathname = Utils.getAttachedFilesDir(filepath) + filename;
    String ext = Utils.getExtensionArchivo(originalName);
    if (StringUtils.isNotBlank(ext)) {
        String str = ext.toLowerCase();
        if (StringUtils.containsOnly(str, validChars)) {
            filename += "." + str;
            pathname += "." + str;
        }
    }
    /**/
    //      part.write(pathname);
    /**/
    //      OutputStream outputStream = new FileOutputStream(pathname);
    //      outputStream.write(IOUtils.readFully(part.getInputStream(), -1, false));
    /**/
    int bytesRead;
    int bufferSize = 8192;
    byte[] bytes = null;
    byte[] buffer = new byte[bufferSize];
    try (InputStream input = part.getInputStream(); OutputStream output = new FileOutputStream(pathname)) {
        while ((bytesRead = input.read(buffer)) != -1) {
            if (!EnumOpcionUpload.FILA.equals(opcion)) {
                output.write(buffer, 0, bytesRead);
            }
            if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) {
                if (bytesRead < bufferSize) {
                    bytes = ArrayUtils.addAll(bytes, ArrayUtils.subarray(buffer, 0, bytesRead));
                } else {
                    bytes = ArrayUtils.addAll(bytes, buffer);
                }
            }
        }
    }
    /**/
    String clientFilePath = null;
    String clientFileName = clientFilePath == null ? originalName : clientFilePath + originalName;
    String serverFileName = Utils.getWebServerRelativePath(pathname);
    if (!EnumOpcionUpload.ARCHIVO.equals(opcion)) {
        String contentType = part.getContentType();
        long size = part.getSize();
        insert(id, clientFileName, serverFileName, contentType, size, bytes);
    }
    campoArchivo.setClientFileName(clientFileName);
    campoArchivo.setServerFileName(serverFileName);
    return campoArchivo;
}

From source file:br.unicamp.ic.recod.gpsi.applications.gpsiJGAPEvolver.java

private GPGenotype create(GPConfiguration conf, int n_bands, gpsiJGAPFitnessFunction fitness)
        throws InvalidConfigurationException {

    Class[] types = { CommandGene.DoubleClass };
    Class[][] argTypes = { {} };// w  ww. jav a  2s  .  co m

    CommandGene[] variables = new CommandGene[n_bands];

    Variable[] b = new Variable[n_bands];
    CommandGene[] functions = { new Add(conf, CommandGene.DoubleClass),
            new Subtract(conf, CommandGene.DoubleClass), new Multiply(conf, CommandGene.DoubleClass),
            new gpsiJGAPProtectedDivision(conf, CommandGene.DoubleClass),
            new gpsiJGAPProtectedNaturalLogarithm(conf, CommandGene.DoubleClass),
            new gpsiJGAPProtectedSquareRoot(conf, CommandGene.DoubleClass),
            new Terminal(conf, CommandGene.DoubleClass, 1.0d, 1000000.0d, false) };

    for (int i = 0; i < n_bands; i++) {
        b[i] = Variable.create(conf, "b" + i, CommandGene.DoubleClass);
        variables[i] = b[i];
    }

    CommandGene[][] nodeSets = new CommandGene[1][];
    nodeSets[0] = (CommandGene[]) ArrayUtils.addAll(variables, functions);

    fitness.setB(b);

    return GPGenotype.randomInitialGenotype(conf, types, argTypes, nodeSets, 100, true);
}

From source file:de.ingrid.admin.elasticsearch.IndexImpl.java

@Override
public IngridHitDetail getDetail(IngridHit hit, IngridQuery ingridQuery, String[] requestedFields) {
    for (int i = 0; i < requestedFields.length; i++) {
        requestedFields[i] = requestedFields[i].toLowerCase();
    }//from ww  w.  j a  v a  2s.c  o  m
    String documentId = hit.getDocumentId();
    String fromIndex = hit.getString(ELASTIC_SEARCH_INDEX);
    String fromType = hit.getString(ELASTIC_SEARCH_INDEX_TYPE);
    String[] allFields = (String[]) ArrayUtils.addAll(detailFields, requestedFields);

    // We have to search here again, to get a highlighted summary of the result!
    QueryBuilder query = QueryBuilders.boolQuery()
            .must(QueryBuilders.matchQuery(IngridDocument.DOCUMENT_UID, documentId))
            .must(queryConverter.convert(ingridQuery));

    // search prepare
    SearchRequestBuilder srb = indexManager.getClient().prepareSearch(fromIndex).setTypes(fromType)
            .setSearchType(searchType).setQuery(query) // Query
            .setFrom(0).setSize(1).addHighlightedField(config.indexFieldSummary).addFields(allFields)
            .setExplain(false);

    SearchResponse searchResponse = srb.execute().actionGet();

    SearchHits dHits = searchResponse.getHits();
    SearchHit dHit = dHits.getAt(0);

    String title = "untitled";
    if (dHit.field(config.indexFieldTitle) != null) {
        title = (String) dHit.field(config.indexFieldTitle).getValue();
    }
    String summary = "";
    // try to get the summary first from the highlighted fields
    if (dHit.getHighlightFields().containsKey(config.indexFieldSummary)) {
        summary = StringUtils.join(dHit.getHighlightFields().get(config.indexFieldSummary).fragments(),
                " ... ");
        // otherwise get it from the original field
    } else if (dHit.field(config.indexFieldSummary) != null) {
        summary = (String) dHit.field(config.indexFieldSummary).getValue();
    }

    IngridHitDetail detail = new IngridHitDetail(hit, title, summary);

    addPlugDescriptionInformations(detail, requestedFields);

    detail.setDocumentId(documentId);
    if (requestedFields != null) {
        for (String field : requestedFields) {
            if (dHit.field(field) != null) {
                if (dHit.field(field).getValues() instanceof List) {
                    if (dHit.field(field).getValues().size() > 1) {
                        detail.put(field, dHit.field(field).getValues());
                    } else {
                        if (dHit.field(field).getValue() instanceof String) {
                            detail.put(field, new String[] { dHit.field(field).getValue() });
                        } else {
                            detail.put(field, dHit.field(field).getValue());
                        }
                    }
                } else if (dHit.field(field).getValue() instanceof String) {
                    detail.put(field, new String[] { dHit.field(field).getValue() });
                } else {
                    detail.put(field, dHit.field(field).getValue());
                }
            }
        }
    }

    // add additional fields to detail object (such as url for iPlugSE)
    for (String extraDetail : config.additionalSearchDetailFields) {
        SearchHitField field = dHit.getFields().get(extraDetail);
        if (field != null) {
            detail.put(extraDetail, field.getValue());
        }
    }

    return detail;
}

From source file:com.linkedin.restli.examples.TestGreetingsClientAcceptTypes.java

@DataProvider(name = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX
        + "clientDataDataProvider")
public Object[][] clientDataDataProvider() {
    // combine oldBuildersClientDataDataProvider and newBuildersClientDataDataProvider and wrap the builders in RootBuilderWrappers
    final int builderIndex = 2;
    Object[][] oldBuildersDataProvider = oldBuildersClientDataDataProvider();
    Object[][] newBuildersDataProvider = newBuildersClientDataDataProvider();
    Object[][] result = new Object[oldBuildersDataProvider.length + newBuildersDataProvider.length][];

    int currResultIndex = 0;
    for (Object[] arguments : (Object[][]) ArrayUtils.addAll(oldBuildersDataProvider,
            newBuildersDataProvider)) {/*from w  ww  .  jav a  2  s . c o m*/
        Object[] newArguments = arguments;
        newArguments[builderIndex] = new RootBuilderWrapper<Long, Greeting>(newArguments[builderIndex]);
        result[currResultIndex] = newArguments;
        currResultIndex++;
    }

    return result;
}

From source file:com.blockwithme.longdb.leveldb.LevelDBTable.java

/** method for update/insert row-column combination */
private void setOnly(final long theKey, final Columns theInsertUpdateColumns) {
    try {//from   w w w .  j  a v a 2  s .co m
        for (final LongHolder longCursor : theInsertUpdateColumns) {
            // update blob with the combined key
            final byte[] rowColumnPair = Util.combine(theKey, longCursor.value());
            final Bytes byts = theInsertUpdateColumns.getBytes(longCursor.value());
            assert (byts != null);
            final byte[] valueBytes = byts.toArray(false);
            dbInstance.put(rowColumnPair, valueBytes, writeOpts);
            // update column Id list.
            final Bytes rowIdBytes = new Bytes(Util.toByta(theKey));
            final Bytes colIdBytes = new Bytes(Util.toByta(longCursor.value()));
            // TODO use dbInstance.write() instead of delete()/put().
            // write() uses WriteBatch to 'batch' all the db updates
            // belonging to a single transaction.
            if (dbInstance.get(toArray(rowIdBytes), readOpts) == null) {
                dbInstance.put(toArray(rowIdBytes), toArray(colIdBytes), writeOpts);
            } else {
                final ReadOptions readOptsNoCache = new ReadOptions();
                readOptsNoCache.fillCache(false);

                final byte[] allColIds = dbInstance.get(toArray(rowIdBytes), readOptsNoCache);
                if (allColIds == null || allColIds.length == 0) {
                    dbInstance.put(toArray(rowIdBytes), toArray(colIdBytes), writeOpts);
                } else {
                    final long position = Util.indexOf(allColIds, longCursor.value());
                    if (position < 0) {
                        final byte[] newColIds = ArrayUtils.addAll(allColIds, toArray(colIdBytes));
                        dbInstance.put(toArray(rowIdBytes), newColIds, writeOpts);
                    }
                }
            }
        }
    } catch (final Exception e) {
        LOG.error("Exception Occurred in - setOnly(long key=" + theKey + ", Columns insertOrUpdate="
                + theInsertUpdateColumns + ")", e);
        throw new DBException("Error Performaing Insert Update Operation.", e);
    }
}