Example usage for java.util Map putAll

List of usage examples for java.util Map putAll

Introduction

In this page you can find the example usage for java.util Map putAll.

Prototype

void putAll(Map<? extends K, ? extends V> m);

Source Link

Document

Copies all of the mappings from the specified map to this map (optional operation).

Usage

From source file:cn.fql.utility.CollectionUtility.java

/**
 * check each element of first list, and compare it to each element of second list.
 * element of list is <code>java.util.Map</code>, get value from map by specified key, if value
 * of element of first list are equals second's, invoke <code>java.util.Map#putAll</code>
 * of element of first list/* w w  w.  j  ava 2 s .  c o  m*/
 *
 * @param first  first collection
 * @param second second collection
 * @param key    specified key
 * @return first list
 */
public static List joinRecords(List first, List second, String key) {
    if (first != null && second != null) {
        for (int i = 0; i < first.size(); i++) {
            Map record1 = (Map) first.get(i);
            for (Iterator iterator1 = second.iterator(); iterator1.hasNext();) {
                Map record2 = (Map) iterator1.next();
                if (record2.get(key) != null && record2.get(key).equals(record1.get(key))) {
                    record1.putAll(record2);
                    break;
                }
            }
            first.set(i, record1);
        }
    }
    return first;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.util.OffsetQueryUtil.java

/**
 * Build query using the lastOffset which is of the form (<column1>=<value1>::<column2>=<value2>::<column3>=<value3>)
 *
 * @param tableRuntimeContext Context for the current table.
 * @param lastOffset the last offset for this particular table
 * @return A query to execute for the current batch.
 *///from   w w w.j  a  v a2  s. c  om
public static Pair<String, List<Pair<Integer, String>>> buildAndReturnQueryAndParamValToSet(
        TableRuntimeContext tableRuntimeContext, String lastOffset, String quoteChar,
        TableJdbcELEvalContext tableJdbcELEvalContext) throws ELEvalException {
    final TableContext tableContext = tableRuntimeContext.getSourceTableContext();
    StringBuilder queryBuilder = new StringBuilder();
    List<Pair<Integer, String>> paramValueToSet = new ArrayList<>();
    queryBuilder.append(buildBaseTableQuery(tableRuntimeContext, quoteChar));

    Map<String, String> storedTableToOffset = getColumnsToOffsetMapFromOffsetFormat(lastOffset);
    final boolean noStoredOffsets = storedTableToOffset.isEmpty();

    //Determines whether an initial offset is specified in the config and there is no stored offset.
    boolean isOffsetOverriden = tableContext.isOffsetOverriden() && noStoredOffsets;

    OffsetComparison minComparison = OffsetComparison.GREATER_THAN;
    Map<String, String> offset = null;
    if (isOffsetOverriden) {
        //Use the offset in the configuration
        offset = tableContext.getOffsetColumnToStartOffset();
    } else if (tableRuntimeContext.isPartitioned() && noStoredOffsets) {
        // use partitioned starting offsets
        offset = tableRuntimeContext.getStartingPartitionOffsets();
        minComparison = OffsetComparison.GREATER_THAN_OR_EQUALS;
    } else {
        // if offset is available
        // get the stored offset (which is of the form partitionName=value) and strip off 'offsetColumns=' prefix
        // else null
        // offset = storedOffsets;
        offset = storedTableToOffset;
    }

    Map<String, String> maxOffsets = new HashMap<>();
    if (tableRuntimeContext.isPartitioned()) {
        maxOffsets.putAll(tableRuntimeContext.getMaxPartitionOffsets());
    }

    List<String> finalAndConditions = new ArrayList<>();
    //Apply last offset conditions
    if (offset != null && !offset.isEmpty()) {
        List<String> finalOrConditions = new ArrayList<>();
        List<String> preconditions = new ArrayList<>();
        List<Pair<Integer, String>> preconditionParamVals = new ArrayList<>();
        //For partition columns p1, p2 and p3 with offsets o1, o2 and o3 respectively, the query will look something like
        //select * from tableName where (p1 > o1) or (p1 = o1 and p2 > o2) or (p1 = o1 and p2 = o2 and p3 > o3) order by p1, p2, p3.
        for (String partitionColumn : tableContext.getOffsetColumns()) {
            int partitionSqlType = tableContext.getOffsetColumnType(partitionColumn);
            String partitionOffset = offset.get(partitionColumn);

            String thisPartitionColumnMax = null;
            boolean hasMaxOffset = false;
            // add max value for partition column (if applicable)
            if (maxOffsets.containsKey(partitionColumn)) {
                final String maxOffset = maxOffsets.get(partitionColumn);
                if (!Strings.isNullOrEmpty(maxOffset)) {
                    Pair<Integer, String> paramValForCurrentOffsetColumnMax = Pair.of(partitionSqlType,
                            maxOffset);
                    // add for current partition column max value
                    paramValueToSet.add(paramValForCurrentOffsetColumnMax);
                    thisPartitionColumnMax = getConditionForPartitionColumn(partitionColumn,
                            OffsetComparison.LESS_THAN, preconditions, quoteChar);
                    hasMaxOffset = true;
                }
            }

            final String thisPartitionColumnMin = getConditionForPartitionColumn(partitionColumn, minComparison,
                    preconditions, quoteChar);

            String conditionForThisPartitionColumn;
            if (hasMaxOffset) {
                conditionForThisPartitionColumn = String.format(AND_CONDITION_FORMAT,
                        // add max condition first, since its param to set was already added
                        thisPartitionColumnMax, thisPartitionColumnMin);
            } else {
                conditionForThisPartitionColumn = String.format(CONDITION_FORMAT, thisPartitionColumnMin);
            }

            //Add for preconditions (EX: composite keys)
            paramValueToSet.addAll(new ArrayList<>(preconditionParamVals));
            Pair<Integer, String> paramValForCurrentOffsetColumn = Pair.of(partitionSqlType, partitionOffset);
            //Add for current partition column
            paramValueToSet.add(paramValForCurrentOffsetColumn);
            finalOrConditions.add(conditionForThisPartitionColumn);
            preconditions.add(getConditionForPartitionColumn(partitionColumn, OffsetComparison.EQUALS,
                    Collections.emptyList(), quoteChar));

            preconditionParamVals.add(paramValForCurrentOffsetColumn);
        }
        finalAndConditions.add(String.format(CONDITION_FORMAT, OR_JOINER.join(finalOrConditions)));
    }

    if (!StringUtils.isEmpty(tableContext.getExtraOffsetColumnConditions())) {
        //Apply extra offset column conditions configured which will be appended as AND on the query
        String condition = tableJdbcELEvalContext.evaluateAsString("extraOffsetColumnConditions",
                tableContext.getExtraOffsetColumnConditions());
        finalAndConditions.add(String.format(CONDITION_FORMAT, condition));
    }

    if (!finalAndConditions.isEmpty()) {
        queryBuilder.append(String.format(WHERE_CLAUSE, AND_JOINER.join(finalAndConditions)));
    }

    Collection<String> quotedOffsetColumns = tableContext.getOffsetColumns().stream()
            .map(offsetCol -> String.format(QUOTED_NAME, quoteChar, offsetCol, quoteChar))
            .collect(Collectors.toList());

    queryBuilder.append(String.format(ORDER_BY_CLAUSE, COMMA_SPACE_JOINER.join(quotedOffsetColumns)));
    return Pair.of(queryBuilder.toString(), paramValueToSet);
}

From source file:com.dynamobi.db.conn.couchdb.CouchUdx.java

/**
 * This method handles merges for three types of forms of
 * key/values with a passed in set of params for full-column coverage.
 *
 * @param params - eventual json dict/*from   ww w. j a  v a2 s  .  c o  m*/
 * @param kv - key or value in key-value pair
 * @param prefix - prefix to use to have ordered keys/values
 * @return Returns the number of "duplicates"; that is, how many
 * values are now pointed at by two keys instead of one. This will
 * be 0 unless we have a mix of named and positional in an array.
 */
private static int mergeParams(Map<String, Object> params, Object kv, String prefix) {
    if (kv instanceof JSONObject) {
        // merges {'x': v, 'y': v2, ...} with params, cannot rely on order.
        params.putAll((JSONObject) kv);
    } else if (kv instanceof JSONArray) {
        // merges each of [ {'x': v}, v2, ... ] with params, assigning each
        // element in the array to prefix+idx as well. However, if
        // an object contains {'x': v, 'y': v2}, prefix+idx will refer to the
        // whole object currently.
        int i = 0;
        int dupes = 0;
        for (Object ob : (JSONArray) kv) {
            if (ob instanceof JSONObject) {
                params.putAll((JSONObject) ob);
                dupes++;
            }
            params.put(prefix + (i++), ob);
        }
        return dupes;
    } else {
        // merges 'x' or 3.4 or some single-value thing and gives it the 0th idx
        params.put(prefix + "0", kv);
    }
    return 0;
}

From source file:com.seajas.search.utilities.ui.InterfaceQueryUtils.java

/**
 * Create a combined map containing both the parameters and taxonomy IDs.
 * /*from  w w w . j  a va  2 s .c  om*/
 * @param parameters
 * @param taxonomyIdentifiers
 * @return Map<String, String>
 */
public static Map<String, String> combineParametersAndTaxonomies(final Map<String, String> parameters,
        final List<Integer> taxonomyIdentifiers) {
    Map<String, String> result = new HashMap<String, String>();

    if (taxonomyIdentifiers.size() > 0) {
        String taxonomyIds = "";

        for (Integer taxonomyIdentifier : taxonomyIdentifiers)
            taxonomyIds += (taxonomyIds.equals("") ? "" : " ") + taxonomyIdentifier;

        if (!StringUtils.isBlank(taxonomyIds))
            result.put("dcterms_coverage", taxonomyIds.trim());
        else
            result.put("dcterms_coverage", "1 2"); // Active, Unassigned
    }

    result.putAll(parameters);

    return result;
}

From source file:com.bosscs.spark.commons.utils.Utils.java

/**
 * Returns an instance clone.//  ww  w. j  a  va  2  s  .c o  m
 * this method gets every class property by reflection, including its parents properties
 * @param t
 * @param <T>
 * @return T object.
 */
public static <T> T cloneObjectWithParents(T t) throws IllegalAccessException, InstantiationException {
    T clone = (T) t.getClass().newInstance();

    List<Field> allFields = new ArrayList<>();

    Class parentClass = t.getClass().getSuperclass();

    while (parentClass != null) {
        Collections.addAll(allFields, parentClass.getDeclaredFields());
        parentClass = parentClass.getSuperclass();
    }

    Collections.addAll(allFields, t.getClass().getDeclaredFields());

    for (Field field : allFields) {
        int modifiers = field.getModifiers();
        //We skip final and static fields
        if ((Modifier.FINAL & modifiers) != 0 || (Modifier.STATIC & modifiers) != 0) {
            continue;
        }
        field.setAccessible(true);

        Object value = field.get(t);

        if (Collection.class.isAssignableFrom(field.getType())) {
            Collection collection = (Collection) field.get(clone);
            if (collection == null) {
                collection = (Collection) field.get(t).getClass().newInstance();
            }
            collection.addAll((Collection) field.get(t));
            value = collection;
        } else if (Map.class.isAssignableFrom(field.getType())) {
            Map clonMap = (Map) field.get(t).getClass().newInstance();
            clonMap.putAll((Map) field.get(t));
            value = clonMap;
        }
        field.set(clone, value);
    }

    return clone;
}

From source file:com.siemens.sw360.commonIO.TypeMappings.java

@NotNull
public static Map<Integer, Risk> getIntegerRiskMap(LicenseService.Iface licenseClient,
        Map<Integer, RiskCategory> riskCategoryMap, InputStream in) throws TException {
    List<CSVRecord> riskRecords = ImportCSV.readAsCSVRecords(in);
    final List<Risk> risksToAdd = ConvertRecord.convertRisks(riskRecords, riskCategoryMap);
    final List<Risk> risks = CommonUtils.nullToEmptyList(licenseClient.getRisks());
    Map<Integer, Risk> riskMap = Maps.newHashMap(Maps.uniqueIndex(risks, getRiskIdentifier()));
    final ImmutableList<Risk> filteredList = getElementsWithIdentifiersNotInMap(getRiskIdentifier(), riskMap,
            risksToAdd);/*from  w  ww  .ja  v  a 2  s  . c o  m*/
    List<Risk> addedRisks = null;
    if (filteredList.size() > 0) {
        addedRisks = licenseClient.addRisks(filteredList);
    }
    if (addedRisks != null)
        riskMap.putAll(Maps.uniqueIndex(addedRisks, getRiskIdentifier()));
    return riskMap;
}

From source file:com.github.strawberry.guice.config.ConfigLoader.java

private static Map<?, ?> mapOf(Field field, Map properties, String key) {
    Map map = mapImplementationOf(field.getType());

    Object o = properties.get(key);
    if (o instanceof Map) {
        Option<Type> valueType = genericTypeOf(field, 1);
        if (valueType.exists(isAssignableTo(Map.class)) || valueType.exists(isEqualTo(Object.class))) {
            map.put(key, o);//from  ww w . ja  va 2 s  .  c o  m
        } else {
            map.putAll((Map) o);
        }
    } else {
        map.put(key, o);
    }

    return map;
}

From source file:com.alibaba.wasp.meta.TestFMetaStore.java

public static Map<String, String> clone(Map<String, String> parameters) {
    Map<String, String> clone = new HashMap<String, String>();
    clone.putAll(parameters);
    return clone;
}

From source file:com.datatorrent.stram.support.StramTestSupport.java

public static void setEnv(Map<String, String> newenv) throws Exception {
    try {//from   w  ww . jav a  2  s  . com
        Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
        theEnvironmentField.setAccessible(true);
        Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
        env.putAll(newenv);
        Field theCaseInsensitiveEnvironmentField = processEnvironmentClass
                .getDeclaredField("theCaseInsensitiveEnvironment");
        theCaseInsensitiveEnvironmentField.setAccessible(true);
        Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
        cienv.putAll(newenv);
    } catch (NoSuchFieldException e) {
        Class[] classes = Collections.class.getDeclaredClasses();
        Map<String, String> env = System.getenv();
        for (Class cl : classes) {
            if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                Field field = cl.getDeclaredField("m");
                field.setAccessible(true);
                Object obj = field.get(env);
                Map<String, String> map = (Map<String, String>) obj;
                map.clear();
                map.putAll(newenv);
            }
        }
    }
}

From source file:com.thinkbiganalytics.nifi.rest.support.NifiProcessUtil.java

/**
 * Return a map of processGroupId to process group
 *
 * @param template a template to parse/*from  w w w.ja v a2  s. c  o  m*/
 * @return a map of processGroupId to process group
 */
public static Map<String, ProcessGroupDTO> getProcessGroupsMap(TemplateDTO template) {
    Map<String, ProcessGroupDTO> groups = new HashMap<>();
    if (template.getSnippet().getProcessGroups() != null) {
        for (ProcessGroupDTO groupDTO : template.getSnippet().getProcessGroups()) {
            groups.putAll(getProcessGroupsMap(groupDTO));
        }
    }
    return groups;
}