Java Code Examples for java.util.Map.putAll()

The following are Jave code examples for showing how to use putAll() of the java.util.Map class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: alfresco-repository   File: AuditApplication.java   View Source Code Vote up 7 votes
/**
 * Get all data generators applicable to a given path and scope.
 * 
 * @param paths             the audit paths
 * @return                  Returns all data generators mapped to their key-path
 */
public Map<String, DataGenerator> getDataGenerators(Set<String> paths)
{
    Map<String, DataGenerator> amalgamatedGenerators = new HashMap<String, DataGenerator>(13);
    for (String path : paths)
    {
        Map<String, DataGenerator> generators = dataGenerators.get(path);
        if (generators != null)
        {
            // Copy values to combined map
            amalgamatedGenerators.putAll(generators);
        }
    }
    
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug(
                "Looked up data generators: \n" +
                "   Paths:  " + paths + "\n" +
                "   Found: " + amalgamatedGenerators);
    }
    return amalgamatedGenerators;
}
 
Example 2
Project: kafka-0.11.0.0-src-with-comment   File: StringConverter.java   View Source Code Vote up 6 votes
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
    Map<String, Object> serializerConfigs = new HashMap<>();
    serializerConfigs.putAll(configs);
    Map<String, Object> deserializerConfigs = new HashMap<>();
    deserializerConfigs.putAll(configs);

    Object encodingValue = configs.get("converter.encoding");
    if (encodingValue != null) {
        serializerConfigs.put("serializer.encoding", encodingValue);
        deserializerConfigs.put("deserializer.encoding", encodingValue);
    }

    serializer.configure(serializerConfigs, isKey);
    deserializer.configure(deserializerConfigs, isKey);
}
 
Example 3
Project: wavemaker-app-build-tools   File: ModelHandler.java   View Source Code Vote up 6 votes
private Map<String, Property> buildProperties(Model model, Map<String, Property> properties) {

        if (model != null) {
            //some times model can be composed,Composed means if a class inherits another class or interface.
            if (model instanceof ComposedModel) {
                List<Model> allModels = ((ComposedModel) model).getAllOf();
                for (Model eachModel : allModels) {
                    properties.putAll(buildProperties(eachModel, properties));
                }
            } else if (model instanceof RefModel) {
                buildProperties(definitions.get(((RefModel) model).getSimpleRef()), properties);
            } else {
                // in other models such as array,modelImpl,abstract getting properties are straight forward.
                if (model.getProperties() != null) {
                    properties.putAll(model.getProperties());
                }
            }
        }

        return properties;
    }
 
Example 4
Project: monarch   File: LauncherLifecycleCommands.java   View Source Code Vote up 6 votes
private Map<String, String> loadConfigurationProperties(
    final String configurationPropertiesPathname, Map<String, String> configurationProperties) {
  configurationProperties =
      (configurationProperties != null ? configurationProperties : new HashMap<String, String>());

  if (IOUtils.isExistingPathname(configurationPropertiesPathname)) {
    try {
      configurationProperties.putAll(ShellCommands
          .loadPropertiesFromURL(new File(configurationPropertiesPathname).toURI().toURL()));
    } catch (MalformedURLException ignore) {
      LogWrapper.getInstance()
          .warning(String.format(
              "Failed to load GemFire configuration properties from pathname (%1$s)!",
              configurationPropertiesPathname), ignore);
    }
  }

  return configurationProperties;
}
 
Example 5
Project: incubator-netbeans   File: HintTest.java   View Source Code Vote up 6 votes
private ModificationResult runJavaFix(final JavaFix jf) throws IOException {
    FileObject file = Accessor.INSTANCE.getFile(jf);
    JavaSource js = JavaSource.forFileObject(file);
    final Map<FileObject, List<Difference>> changes = new HashMap<FileObject, List<Difference>>();

    ModificationResult mr = js.runModificationTask(new Task<WorkingCopy>() {
        public void run(WorkingCopy wc) throws Exception {
            if (wc.toPhase(Phase.RESOLVED).compareTo(Phase.RESOLVED) < 0) {
                return;
            }

            Map<FileObject, byte[]> resourceContentChanges = new HashMap<FileObject, byte[]>();
            Accessor.INSTANCE.process(jf, wc, true, resourceContentChanges, /*Ignored for now:*/new ArrayList<RefactoringElementImplementation>());
            BatchUtilities.addResourceContentChanges(resourceContentChanges, changes);
            
        }
    });
    
    changes.putAll(JavaSourceAccessor.getINSTANCE().getDiffsFromModificationResult(mr));
    
    return JavaSourceAccessor.getINSTANCE().createModificationResult(changes, Collections.<Object, int[]>emptyMap());
}
 
Example 6
Project: openjdk-jdk10   File: SystemModuleFinders.java   View Source Code Vote up 6 votes
/**
 * Generates a map of module name to hash value.
 */
static Map<String, byte[]> generateNameToHash(ModuleHashes[] recordedHashes) {
    Map<String, byte[]> nameToHash = null;

    boolean secondSeen = false;
    // record the hashes to build HashSupplier
    for (ModuleHashes mh : recordedHashes) {
        if (mh != null) {
            // if only one module contain ModuleHashes, use it
            if (nameToHash == null) {
                nameToHash = mh.hashes();
            } else {
                if (!secondSeen) {
                    nameToHash = new HashMap<>(nameToHash);
                    secondSeen = true;
                }
                nameToHash.putAll(mh.hashes());
            }
        }
    }
    return (nameToHash != null) ? nameToHash : Collections.emptyMap();
}
 
Example 7
Project: para-search-elasticsearch   File: ElasticSearchUtils.java   View Source Code Vote up 6 votes
/**
 * Converts the source of an ES document to {@link ParaObject}.
 * @param <P> object type
 * @param source a map of keys and values coming from ES
 * @return a new ParaObject
 */
static <P extends ParaObject> P getParaObjectFromSource(Map<String, Object> source) {
	if (source == null) {
		return null;
	}
	Map<String, Object> data = new HashMap<>(source.size());
	data.putAll(source);
	// retrieve the JSON for the original properties field and deserialize it
	if (nestedMode() && data.containsKey(PROPS_JSON)) {
		try {
			Map<String, Object> props = ParaObjectUtils.getJsonReader(Map.class).
					readValue((String) data.get(PROPS_JSON));
			data.put(PROPS_FIELD, props);
		} catch (Exception e) {
			logger.error(null, e);
		}
		data.remove(PROPS_JSON);
	}
	data.remove("_docid");
	return ParaObjectUtils.setAnnotatedFields(data);
}
 
Example 8
Project: aamg   File: GenerateAaMigration.java   View Source Code Vote up 6 votes
/**
 * Use grep to see all the files that contain TypeSerializer, and collect them all
 */
private static Map<String, String> getCustomTypes() throws IOException {
    String line;
    Map<String, String> types = new HashMap<>();
    ProcessBuilder builder = new ProcessBuilder("grep", "-rlP", "extends\\s+TypeSerializer");
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));

    // This grep command will output only the file names of the files that contain a TypeSerializer
    while (true) {
        line = r.readLine();
        if (line == null) {
            break;
        }
        // Add all the custom types contained in that file
        types.putAll(getCustomTypes(line));
    }

    return types;
}
 
Example 9
Project: kafka-0.11.0.0-src-with-comment   File: ConsumerConfig.java   View Source Code Vote up 5 votes
public static Map<String, Object> addDeserializerToConfig(Map<String, Object> configs,
                                                          Deserializer<?> keyDeserializer,
                                                          Deserializer<?> valueDeserializer) {
    Map<String, Object> newConfigs = new HashMap<String, Object>();
    newConfigs.putAll(configs);
    if (keyDeserializer != null)
        newConfigs.put(KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializer.getClass());
    if (valueDeserializer != null)
        newConfigs.put(VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializer.getClass());
    return newConfigs;
}
 
Example 10
Project: CodeBroker   File: CacheManager.java   View Source Code Vote up 5 votes
private Map<String, String> getStringStringMap(String index) {
    Jedis jedis = getJedis();

    MapStructure<String> mapStructure = RedisStrutureBuilder.ofMap(jedis, String.class).withNameSpace(nameSpace).build();
    Map<String, String> map = mapStructure.get(index);

    Map<String, String> result = new HashMap<>();
    result.putAll(map);
    if (jedis != null) {
        jedis.close();
    }

    return result;
}
 
Example 11
Project: open-kilda   File: FlowsResource.java   View Source Code Vote up 5 votes
@Get("json")
@SuppressWarnings("unchecked")
public Map<String, Object> getFlows() {
    Map<String, Object> response = new HashMap<>();
    String switchId = (String) this.getRequestAttributes().get("switch_id");
    logger.debug("Get flows for switch: {}", switchId);
    ISwitchManager switchManager = (ISwitchManager) getContext().getAttributes()
            .get(ISwitchManager.class.getCanonicalName());

    try {
        OFFlowStatsReply replay = switchManager.dumpFlowTable(DatapathId.of(switchId));
        logger.debug("OF_STATS: {}", replay);

        if (replay != null) {
            for (OFFlowStatsEntry entry : replay.getEntries()) {
                String key = String.format("flow-0x%s",
                        Long.toHexString(entry.getCookie().getValue()).toUpperCase());
                response.put(key, buildFlowStat(entry));
            }
        }
    } catch (IllegalArgumentException exception) {
        String messageString = "No such switch";
        logger.error("{}: {}", messageString, switchId, exception);
        MessageError responseMessage = new MessageError(DEFAULT_CORRELATION_ID, System.currentTimeMillis(),
                ErrorType.PARAMETERS_INVALID.toString(), messageString, exception.getMessage());
        response.putAll(MAPPER.convertValue(responseMessage, Map.class));
    }
    return response;
}
 
Example 12
Project: lambda-monitoring   File: GenerateMetricFiltersMojo.java   View Source Code Vote up 5 votes
@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    checkConfiguration();

    MetricFilterPublisher publisher =
            dryRun ? new DryRunMetricFilterPublisher(getLog()) :
                    new GenerateMetricFilterPublisher(getLog(),
                            new File(project.getBuild().getDirectory()));

    // Gets a map of fully-namespaced metric names -> annotated fields in classes that extend LambdaMetricSet
    Map<String, Field> metricFields = new HashMap<>();
    try {
        metricFields.putAll(new MetricsFinder(project).find());
    } catch (DependencyResolutionRequiredException | MalformedURLException e) {
        throw new MojoExecutionException("Could not scan classpath for metric fields", e);
    }

    if (!metricFields.isEmpty()) {
        getLog().info(String.format("Found [%d] metric fields in classpath.", metricFields.size()));
        List<MetricFilter> metricFilters = getMetricFilters(metricFields);
        getLog().info(String.format("Published [%d] metric filters.",
                publisher.publishMetricFilters(metricFilters)));
    } else {
        getLog().warn("Did not find any metric fields in classpath.");
    }

}
 
Example 13
Project: oscm   File: AuditLogOperationGroupsTest.java   View Source Code Vote up 5 votes
@Test
public void getAvailableOperations() {
    // when
    Map<String, String> operations = new HashMap<String, String>();

    operations.putAll(AuditLogOperationGroups.getInstance()
            .getAvailableOperations());

    // then
    assertAvailableOperations(operations);
}
 
Example 14
Project: lams   File: MysqlDefs.java   View Source Code Vote up 5 votes
static final void appendJdbcTypeMappingQuery(StringBuilder buf, String mysqlTypeColumnName) {

        buf.append("CASE ");
        Map<String, Integer> typesMap = new HashMap<String, Integer>();
        typesMap.putAll(mysqlToJdbcTypesMap);
        typesMap.put("BINARY", Integer.valueOf(Types.BINARY));
        typesMap.put("VARBINARY", Integer.valueOf(Types.VARBINARY));

        Iterator<String> mysqlTypes = typesMap.keySet().iterator();

        while (mysqlTypes.hasNext()) {
            String mysqlTypeName = mysqlTypes.next();
            buf.append(" WHEN ");
            buf.append(mysqlTypeColumnName);
            buf.append("='");
            buf.append(mysqlTypeName);
            buf.append("' THEN ");
            buf.append(typesMap.get(mysqlTypeName));

            if (mysqlTypeName.equalsIgnoreCase("DOUBLE") || mysqlTypeName.equalsIgnoreCase("FLOAT") || mysqlTypeName.equalsIgnoreCase("DECIMAL")
                    || mysqlTypeName.equalsIgnoreCase("NUMERIC")) {
                buf.append(" WHEN ");
                buf.append(mysqlTypeColumnName);
                buf.append("='");
                buf.append(mysqlTypeName);
                buf.append(" unsigned' THEN ");
                buf.append(typesMap.get(mysqlTypeName));
            }
        }

        buf.append(" ELSE ");
        buf.append(Types.OTHER);
        buf.append(" END ");
    }
 
Example 15
Project: CSLMusicModStationCreator   File: StationAdapter.java   View Source Code Vote up 4 votes
@Override
public Station deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    Station station = new Station();
    JsonObject obj = jsonElement.getAsJsonObject();

    Type songCollectionListType = new TypeToken<List<SongCollection>>(){}.getType();
    Type scheduleEntryListType = new TypeToken<List<ScheduleEntry>>(){}.getType();
    Type namedContextConditionsType = new TypeToken<Map<String, ContextCondition>>(){}.getType();
    Type contextListType = new TypeToken<List<ContextEntry>>(){}.getType();

    final Map<String, ContextCondition> namedContextConditions = new HashMap<>();

    station.setName(obj.get("name").getAsString());
    if(obj.has("description"))
        station.setDescription(obj.get("description").getAsString());
    if(obj.has("thumbnail"))
        station.setThumbnail(obj.get("thumbnail").getAsString());
    if(obj.has("collections")){
        List<SongCollection> coll = jsonDeserializationContext.deserialize(obj.get("collections"), songCollectionListType);
        coll.stream().forEach(x -> station.addCollection(x));
    }
    if(obj.has("schedule"))
        station.setSchedule(jsonDeserializationContext.deserialize(obj.get("schedule"), scheduleEntryListType));
    if(obj.has("filters"))
        namedContextConditions.putAll(jsonDeserializationContext.deserialize(obj.get("filters"), namedContextConditionsType));
    if(obj.has("contexts"))
        station.setContexts(jsonDeserializationContext.deserialize(obj.get("contexts"), contextListType));

    for(ContextEntry cont : station.getContexts()) {
        namedContextConditions.putAll(cont.getConditions().getInlinedContextConditions());
    }

    namedContextConditions.keySet().stream().forEach(x -> station.addFilter(x, namedContextConditions.get(x)));

    // Set all necessary parent references
    station.getFilters().values().stream().forEach(x -> x.setStation(station));
    station.getSchedule().stream().forEach(x -> x.setStation(station));
    station.getContexts().stream().forEach(x -> {
        x.setStation(station);
        x.getConditions().setContext(x);
        x.getConditions().getConjunctions().stream().forEach(y -> y.setFormula(x.getConditions()));
    });
    station.getCollections().values().stream().forEach(x -> x.setStation(station));

    return station;
}
 
Example 16
Project: parabuild-ci   File: AnnotationsConfigurator.java   View Source Code Vote up 4 votes
/**
 * Process the @RemoteProxy annotaion on a given class
 * @param clazz The class annotated with @RemoteProxy
 * @param createAnn The annotation
 * @param container The IoC container to configure
 */
private void processCreate(Class<?> clazz, RemoteProxy createAnn, Container container)
{
    Class<? extends Creator> creator = createAnn.creator();
    String creatorClass = creator.getName();
    Map<String, String> creatorParams = getParamsMap(createAnn.creatorParams());
    ScriptScope scope = createAnn.scope();

    CreatorManager creatorManager = (CreatorManager) container.getBean(CreatorManager.class.getName());
    String creatorName = LocalUtil.replace(creatorClass, ".", "_");
    creatorManager.addCreatorType(creatorName, creatorClass);

    Map<String, String> params = new HashMap<String, String>();
    if (NewCreator.class.isAssignableFrom(creator))
    {
        params.put("class", clazz.getName());
    }
    params.putAll(creatorParams);
    params.put("scope", scope.getValue());

    String name = createAnn.name();
    if (name == null || name.length() == 0)
    {
        name = LocalUtil.getShortClassName(clazz);
    }

    try
    {
        log.info("Adding class " + clazz.getName() + " as " + name);
        creatorManager.addCreator(name, creatorName, params);
    }
    catch (Exception ex)
    {
        log.error("Failed to add class as Creator: " + clazz.getName(), ex);
    }

    AccessControl accessControl = (AccessControl) container.getBean(AccessControl.class.getName());
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++)
    {
        if (methods[i].getAnnotation(RemoteMethod.class) != null)
        {
            accessControl.addIncludeRule(name, methods[i].getName());

            Auth authAnn = methods[i].getAnnotation(Auth.class);
            if (authAnn != null)
            {
                accessControl.addRoleRestriction(name, methods[i].getName(), authAnn.role());
            }
        }
    }

    Filters filtersAnn = clazz.getAnnotation(Filters.class);
    if (filtersAnn != null)
    {
        Filter[] fs = filtersAnn.value();
        for (int i = 0; i < fs.length; i++)
        {
            processFilter(fs[i], name, container);
        }
    }
    // process single filter for convenience
    else
    {
        Filter filterAnn = clazz.getAnnotation(Filter.class);
        if (filterAnn != null)
        {
            processFilter(filterAnn, name, container);
        }
    }
}
 
Example 17
Project: axway-b2b-plugins   File: AzureBlobPluggableTransport.java   View Source Code Vote up 4 votes
@Override
public PluggableMessage produce(PluggableMessage pluggableMessage, PluggableMessage returnMessage)
		throws UnableToProduceException {
	log.debug(LOGGER_KEY + "-- Produce --" + _exchangeType);

	String fileName = pluggableMessage.getFilename();
	String destinationDirectory = this.config.getUploadDestination();
	long fileSize = pluggableMessage.getData().length();
	String containerName = this.mBlobContainer.getName();
	boolean status = false;

	if (AzureTransportUtility.isFolderIncluded(fileName)) {
		throw new UnableToProduceException(
				"File name contains special characters used for folders in Azure. Aborting.");
	}

	try {
		fileName = AzureTransportUtility.constructUploadTargetFileName(fileName, destinationDirectory);
		boolean isRegularUploadMode = AzureTransportUtility.isRegularUploadMode(fileSize,
				this.config.getUploadMode());
		Map<String, String> customMetadata = AzureTransportUtility.getCustomMetadata(this.config);
		Map<String, String> pluggableMessageMetadata = pluggableMessage.getMetadata();
		// Sanitize & Update Interchange metadata to match Azure Blob Metadata
		if(this.config.getAppendMetadata().equalsIgnoreCase(PluginConstants.APPEND_METADATA_FLAG_YES)) {
			log.info(LOGGER_KEY + "Appending Interchange metadata to Blob Metadata");
			customMetadata.putAll(AzureTransportUtility.sanitizeMetadata(pluggableMessageMetadata));
		}
		log.info(LOGGER_KEY + "Azure Storage Upload to [" + containerName + "] under path [" + destinationDirectory
				+ "] for file [" + fileName + "] underway");
		if (isRegularUploadMode) {
			status = regularUpload(this.mBlobContainer, fileName, pluggableMessage, customMetadata, fileSize);
		} else {
			status = chunkUpload(this.mBlobContainer, fileName, pluggableMessage, customMetadata, fileSize);
		}
	} finally {
		String msg = LOGGER_KEY + "Azure storage upload completed [" + status + "]";
		log.info(msg);

		returnMessage.setData(new VirtualData(msg.toCharArray()));
	}
	return null;
}
 
Example 18
Project: ProyectoPacientes   File: LoadBalancedConnectionProxy.java   View Source Code Vote up 4 votes
/**
 * Returns a local hosts blacklist, while cleaning up expired records from the global blacklist, or a blacklist with the hosts to be removed.
 * 
 * @return
 *         A local hosts blacklist.
 */
public synchronized Map<String, Long> getGlobalBlacklist() {
    if (!isGlobalBlacklistEnabled()) {
        if (this.hostsToRemove.isEmpty()) {
            return new HashMap<String, Long>(1);
        }
        HashMap<String, Long> fakedBlacklist = new HashMap<String, Long>();
        for (String h : this.hostsToRemove) {
            fakedBlacklist.put(h, System.currentTimeMillis() + 5000);
        }
        return fakedBlacklist;
    }

    // Make a local copy of the blacklist
    Map<String, Long> blacklistClone = new HashMap<String, Long>(globalBlacklist.size());
    // Copy everything from synchronized global blacklist to local copy for manipulation
    synchronized (globalBlacklist) {
        blacklistClone.putAll(globalBlacklist);
    }
    Set<String> keys = blacklistClone.keySet();

    // We're only interested in blacklisted hosts that are in the hostList
    keys.retainAll(this.hostList);

    // Don't need to synchronize here as we using a local copy
    for (Iterator<String> i = keys.iterator(); i.hasNext();) {
        String host = i.next();
        // OK if null is returned because another thread already purged Map entry.
        Long timeout = globalBlacklist.get(host);
        if (timeout != null && timeout < System.currentTimeMillis()) {
            // Timeout has expired, remove from blacklist
            synchronized (globalBlacklist) {
                globalBlacklist.remove(host);
            }
            i.remove();
        }

    }
    if (keys.size() == this.hostList.size()) {
        // return an empty blacklist, let the BalanceStrategy implementations try to connect to everything since it appears that all hosts are
        // unavailable - we don't want to wait for loadBalanceBlacklistTimeout to expire.
        return new HashMap<String, Long>(1);
    }

    return blacklistClone;
}
 
Example 19
Project: jdk8u-jdk   File: RMIConnectorServer.java   View Source Code Vote up 4 votes
/**
 * <p>Returns a client stub for this connector server.  A client
 * stub is a serializable object whose {@link
 * JMXConnector#connect(Map) connect} method can be used to make
 * one new connection to this connector server.</p>
 *
 * @param env client connection parameters of the same sort that
 * could be provided to {@link JMXConnector#connect(Map)
 * JMXConnector.connect(Map)}.  Can be null, which is equivalent
 * to an empty map.
 *
 * @return a client stub that can be used to make a new connection
 * to this connector server.
 *
 * @exception UnsupportedOperationException if this connector
 * server does not support the generation of client stubs.
 *
 * @exception IllegalStateException if the JMXConnectorServer is
 * not started (see {@link #isActive()}).
 *
 * @exception IOException if a communications problem means that a
 * stub cannot be created.
 **/
public JMXConnector toJMXConnector(Map<String,?> env) throws IOException {
    // The serialized for of rmiServerImpl is automatically
    // a RMI server stub.
    if (!isActive()) throw new
        IllegalStateException("Connector is not active");

    // Merge maps
    Map<String, Object> usemap = new HashMap<String, Object>(
            (this.attributes==null)?Collections.<String, Object>emptyMap():
                this.attributes);

    if (env != null) {
        EnvHelp.checkAttributes(env);
        usemap.putAll(env);
    }

    usemap = EnvHelp.filterAttributes(usemap);

    final RMIServer stub=(RMIServer)rmiServerImpl.toStub();

    return new RMIConnector(stub, usemap);
}
 
Example 20
Project: cas-5.1.0   File: AbstractCasView.java   View Source Code Vote up 2 votes
/**
 * Put all into model.
 *
 * @param model  the model
 * @param values the values
 */
protected void putAllIntoModel(final Map<String, Object> model, final Map<String, Object> values) {
    model.putAll(values);
}