Java Code Examples for java.util.Collections#unmodifiableMap()

The following examples show how to use java.util.Collections#unmodifiableMap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExecuteArgAnalyzer.java    From lastaflute with Apache License 2.0 6 votes vote down vote up
protected Map<Integer, Class<?>> prepareOptionalGenericTypeMap(Method executeMethod) {
    final Parameter[] parameters = executeMethod.getParameters();
    if (parameters.length == 0) {
        return Collections.emptyMap();
    }
    final Map<Integer, Class<?>> optionalGenericTypeMap = new LinkedHashMap<Integer, Class<?>>(4);
    int index = 0;
    for (Parameter parameter : parameters) {
        if (isOptionalParameterType(parameter.getType())) {
            final Type paramedType = parameter.getParameterizedType();
            final Class<?> genericType = DfReflectionUtil.getGenericFirstClass(paramedType);
            checkExecuteMethodOptionalParameter(executeMethod, paramedType, genericType);
            optionalGenericTypeMap.put(index, genericType);
        }
        ++index;
    }
    return Collections.unmodifiableMap(optionalGenericTypeMap);
}
 
Example 2
Source File: HttpURLConnection.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private Map<String, List<String>> getFilteredHeaderFields() {
    if (filteredHeaders != null)
        return filteredHeaders;

    Map<String, List<String>> headers, tmpMap = new HashMap<>();

    if (cachedHeaders != null)
        headers = cachedHeaders.getHeaders();
    else
        headers = responses.getHeaders();

    for (Map.Entry<String, List<String>> e: headers.entrySet()) {
        String key = e.getKey();
        List<String> values = e.getValue(), filteredVals = new ArrayList<>();
        for (String value : values) {
            String fVal = filterHeaderField(key, value);
            if (fVal != null)
                filteredVals.add(fVal);
        }
        if (!filteredVals.isEmpty())
            tmpMap.put(key, Collections.unmodifiableList(filteredVals));
    }

    return filteredHeaders = Collections.unmodifiableMap(tmpMap);
}
 
Example 3
Source File: MapType.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public Object getObjectValue(ConnectorSession session, Block block, int position)
{
    if (block.isNull(position)) {
        return null;
    }

    Block singleMapBlock = block.getObject(position, Block.class);
    if (!(singleMapBlock instanceof SingleMapBlock)) {
        throw new UnsupportedOperationException("Map is encoded with legacy block representation");
    }
    Map<Object, Object> map = new HashMap<>();
    for (int i = 0; i < singleMapBlock.getPositionCount(); i += 2) {
        map.put(keyType.getObjectValue(session, singleMapBlock, i), valueType.getObjectValue(session, singleMapBlock, i + 1));
    }

    return Collections.unmodifiableMap(map);
}
 
Example 4
Source File: Languages.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
private Languages(Activity activity) {
    Set<Locale> localeSet = new LinkedHashSet<>();
    localeSet.addAll(Arrays.asList(LOCALES_TO_TEST));

    for (Locale locale : localeSet) {
        if (locale.equals(TIBETAN)) {
            // include English name for devices without Tibetan font support
            tmpMap.put(TIBETAN.getLanguage(), "Tibetan བོད་སྐད།"); // Tibetan
        } else if (locale.equals(Locale.SIMPLIFIED_CHINESE)) {
            tmpMap.put(Locale.SIMPLIFIED_CHINESE.toString(), "中文 (中国)"); // Chinese (China)
        } else if (locale.equals(Locale.TRADITIONAL_CHINESE)) {
            tmpMap.put(Locale.TRADITIONAL_CHINESE.toString(), "中文 (台灣)"); // Chinese (Taiwan)
        } else if (locale.equals(CHINESE_HONG_KONG)) {
            tmpMap.put(CHINESE_HONG_KONG.toString(), "中文 (香港)"); // Chinese (Hong Kong)
        } else {
            tmpMap.put(locale.getLanguage(), capitalize(locale.getDisplayLanguage(locale)));
        }
    }

    // remove the current system language from the menu
    tmpMap.remove(Locale.getDefault().getLanguage());

    /* SYSTEM_DEFAULT is a fake one for displaying in a chooser menu. */
    tmpMap.put(USE_SYSTEM_DEFAULT, activity.getString(R.string.pref_language_default));
    nameMap = Collections.unmodifiableMap(tmpMap);
}
 
Example 5
Source File: TypeConverter.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Null-safely convert between two maps by applying a function to each key and value. A predicate is also specified to filter
 * the results, in case the mapping function were to generate duplicate keys, etc.
 */
public static <T1, T2, U1, U2> Map<U1, U2> convert(Map<T1, T2> toConvert,
                                                   Function<? super T1, ? extends U1> keyConverter,
                                                   Function<? super T2, ? extends U2> valueConverter,
                                                   BiPredicate<U1, U2> resultFilter) {
    if (toConvert == null) {
        return null;
    }

    Map<U1, U2> result = toConvert.entrySet().stream()
                                  .map(e -> new SimpleImmutableEntry<>(keyConverter.apply(e.getKey()),
                                                                       valueConverter.apply(e.getValue())))
                                  .filter(p -> resultFilter.test(p.getKey(), p.getValue()))
                                  .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
    return Collections.unmodifiableMap(result);
}
 
Example 6
Source File: URL.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters) {
	if ((username == null || username.length() == 0) 
			&& password != null && password.length() > 0) {
		throw new IllegalArgumentException("Invalid url, password without username!");
	}
	this.protocol = protocol;
	this.username = username;
	this.password = password;
	this.host = host;
	this.port = (port < 0 ? 0 : port);
	this.path = path;
	// trim the beginning "/"
	while(path != null && path.startsWith("/")) {
	    path = path.substring(1);
	}
	if (parameters == null) {
	    parameters = new HashMap<String, String>();
	} else {
	    parameters = new HashMap<String, String>(parameters);
	}
	this.parameters = Collections.unmodifiableMap(parameters);
}
 
Example 7
Source File: AmountResourcePhaseStorage.java    From mars-sim with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Updates the total amount resource phases stored cache value.
 */
private void updateTotalAmountResourcePhasesStored() {

	double totalAmount = 0D;

	if (amountResourcePhaseStored != null) {
		Map<PhaseType, StoredPhase> tempMap = Collections.unmodifiableMap(amountResourcePhaseStored);
		Iterator<PhaseType> i = tempMap.keySet().iterator();
		while (i.hasNext()) {
			totalAmount += tempMap.get(i.next()).amount;
		}
	}

	totalStoredCache = totalAmount;
	totalStoredCacheDirty = false;
}
 
Example 8
Source File: ConfigResolver.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Map of all properties from all scannable config sources. The values of the properties reflect the
 * values that would be obtained by a call to {@link #getPropertyValue(java.lang.String)}, that is, the value of the
 * property from the ConfigSource with the highest ordinal.
 *
 * @see ConfigSource#isScannable()
 */
public static Map<String, String> getAllProperties()
{
    ConfigSource[] configSources = getConfigProvider().getConfig().getConfigSources();
    Map<String, String> result = new HashMap<String, String>();

    for (int i = configSources.length; i > 0; i--)
    {
        ConfigSource configSource = configSources[i - 1];

        if (configSource.isScannable())
        {
            result.putAll(configSource.getProperties());
        }
    }

    return Collections.unmodifiableMap(result);
}
 
Example 9
Source File: FileBasedVariableRegistry.java    From nifi with Apache License 2.0 5 votes vote down vote up
public FileBasedVariableRegistry(final Path[] propertiesPaths) {
    final Map<VariableDescriptor, String> newMap = new HashMap<>(VariableRegistry.ENVIRONMENT_SYSTEM_REGISTRY.getVariableMap());
    final int systemEnvPropCount = newMap.size();
    int totalPropertiesLoaded = systemEnvPropCount;
    LOG.info("Loaded {} properties from system properties and environment variables",systemEnvPropCount);
    try {
        for (final Path path : propertiesPaths) {
            if (Files.exists(path)) {
                final AtomicInteger propsLoaded = new AtomicInteger(0);
                try (final InputStream inStream = new BufferedInputStream(new FileInputStream(path.toFile()))) {
                    Properties properties = new Properties();
                    properties.load(inStream);
                    properties.entrySet().stream().forEach((entry) -> {
                        final VariableDescriptor desc = new VariableDescriptor.Builder(entry.getKey().toString())
                                .description(path.toString())
                                .sensitive(false)
                                .build();
                        newMap.put(desc, entry.getValue().toString());
                        propsLoaded.incrementAndGet();
                    });
                }
                totalPropertiesLoaded += propsLoaded.get();
                if(propsLoaded.get() > 0){
                    LOG.info("Loaded {} properties from '{}'", propsLoaded.get(), path);
                }else{
                    LOG.warn("No properties loaded from '{}'", path);
                }
            } else {
                LOG.warn("Skipping property file {} as it does not appear to exist", path);
            }
        }
    } catch (final IOException ioe) {
        LOG.error("Unable to complete variable registry loading from files due to ", ioe);
    }

    LOG.info("Loaded a total of {} properties.  Including precedence overrides effective accessible registry key size is {}", totalPropertiesLoaded, newMap.size());
    map = Collections.unmodifiableMap(newMap);
}
 
Example 10
Source File: TCSObject.java    From openAGV with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new TCSObject.
 *
 * @param objectName The new object's name.
 * @param properties A set of properties (key-value pairs) associated with this object.
 * @param history A history of events related to this object.
 */
protected TCSObject(@Nonnull String objectName,
                    @Nonnull Map<String, String> properties,
                    @Nonnull ObjectHistory history) {
  this.name = requireNonNull(objectName, "objectName");
  this.properties = mapWithoutNullValues(properties);
  this.propertiesReadOnly = Collections.unmodifiableMap(this.properties);
  this.id = nextId.getAndIncrement();
  this.reference = new TCSObjectReference<>(this);
  this.history = requireNonNull(history, "history");
}
 
Example 11
Source File: DefaultTwillSpecification.java    From twill with Apache License 2.0 5 votes vote down vote up
public DefaultTwillSpecification(String name, Map<String, RuntimeSpecification> runnables,
                                 List<Order> orders, List<PlacementPolicy> placementPolicies,
                                 EventHandlerSpecification eventHandler) {
  this.name = name;
  this.runnables = Collections.unmodifiableMap(new HashMap<String, RuntimeSpecification>(runnables));
  this.orders = Collections.unmodifiableList(new ArrayList<Order>(orders));
  this.placementPolicies = placementPolicies;
  this.eventHandler = eventHandler;
}
 
Example 12
Source File: AtomicLongMap.java    From cachecloud with Apache License 2.0 5 votes vote down vote up
private Map<K, Long> createAsMap() {
    Map<K,Long> resultMap = new LinkedHashMap<K, Long>();
    if(map != null && !map.isEmpty()){
        for(Entry<K, AtomicLong> entry : map.entrySet()){
            resultMap.put(entry.getKey(), entry.getValue().get());
        }
    }
    return Collections.unmodifiableMap(resultMap);
}
 
Example 13
Source File: FieldInfo.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
private static Map<Integer, String> createFieldTypeNumberMap(Map<String, Integer> fieldTypeByName) { // SCIPIO
    Map<Integer, String> fieldTypeByNumber = new HashMap<>();
    for(Map.Entry<String, Integer> entry : fieldTypeByName.entrySet()) {
        fieldTypeByNumber.put(entry.getValue(), entry.getKey());
    }
    return Collections.unmodifiableMap(fieldTypeByNumber);
}
 
Example 14
Source File: AbstractManagedChannelImplBuilder.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Map<String, ?> checkMapEntryTypes(@Nullable Map<?, ?> map) {
  if (map == null) {
    return null;
  }
  // Not using ImmutableMap.Builder because of extra guava dependency for Android.
  Map<String, Object> parsedMap = new LinkedHashMap<>();
  for (Map.Entry<?, ?> entry : map.entrySet()) {
    checkArgument(
        entry.getKey() instanceof String,
        "The key of the entry '%s' is not of String type", entry);

    String key = (String) entry.getKey();
    Object value = entry.getValue();
    if (value == null) {
      parsedMap.put(key, null);
    } else if (value instanceof Map) {
      parsedMap.put(key, checkMapEntryTypes((Map<?, ?>) value));
    } else if (value instanceof List) {
      parsedMap.put(key, checkListEntryTypes((List<?>) value));
    } else if (value instanceof String) {
      parsedMap.put(key, value);
    } else if (value instanceof Double) {
      parsedMap.put(key, value);
    } else if (value instanceof Boolean) {
      parsedMap.put(key, value);
    } else {
      throw new IllegalArgumentException(
          "The value of the map entry '" + entry + "' is of type '" + value.getClass()
              + "', which is not supported");
    }
  }
  return Collections.unmodifiableMap(parsedMap);
}
 
Example 15
Source File: OCSPResponse.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Map<String, java.security.cert.Extension> getSingleExtensions() {
    return Collections.unmodifiableMap(singleExtensions);
}
 
Example 16
Source File: Offer.java    From flink with Apache License 2.0 4 votes vote down vote up
public Offer(Protos.Offer offer) {
	this.offer = checkNotNull(offer);
	this.hostname = offer.getHostname();
	this.vmID = offer.getSlaveId().getValue();
	this.offeredTime = System.currentTimeMillis();

	List<Protos.Resource> resources = new ArrayList<>(offer.getResourcesList().size());
	Map<String, Double> aggregatedScalarResourceMap = new HashMap<String, Double>() {
		@Override
		public Double remove(Object key) {
			if (super.containsKey(key)) {
				return super.remove(key);
			} else {
				return 0.0;
			}
		}
	};
	Map<String, List<Protos.Resource>> rangesResourceMap = new HashMap<>();
	for (Protos.Resource resource : offer.getResourcesList()) {
		switch (resource.getType()) {
			case SCALAR:
				resources.add(resource);
				aggregatedScalarResourceMap.merge(resource.getName(), resource.getScalar().getValue(), Double::sum);
				break;
			case RANGES:
				resources.add(resource);
				rangesResourceMap.computeIfAbsent(resource.getName(), k -> new ArrayList<>(2)).add(resource);
				break;
			default:
				logger.debug("Unknown resource type " + resource.getType() + " for resource " + resource.getName() +
					" in offer, hostname=" + hostname + ", offerId=" + offer.getId());
		}
	}
	this.resources = Collections.unmodifiableList(resources);

	this.cpuCores = aggregatedScalarResourceMap.remove("cpus");
	this.memoryMB = aggregatedScalarResourceMap.remove("mem");
	this.networkMbps = aggregatedScalarResourceMap.remove("network");
	this.diskMB = aggregatedScalarResourceMap.remove("disk");
	this.aggregatedScalarResourceMap = Collections.unmodifiableMap(aggregatedScalarResourceMap);
	this.portRanges = Collections.unmodifiableList(aggregateRangesResource(rangesResourceMap, "ports"));

	if (offer.getAttributesCount() > 0) {
		Map<String, Protos.Attribute> attributeMap = new HashMap<>();
		for (Protos.Attribute attribute: offer.getAttributesList()) {
			attributeMap.put(attribute.getName(), attribute);
		}
		this.attributeMap = Collections.unmodifiableMap(attributeMap);
	} else {
		this.attributeMap = Collections.emptyMap();
	}
}
 
Example 17
Source File: ChaoShenEntropyEstimator.java    From datafu with Apache License 2.0 4 votes vote down vote up
Map<Long, MutableLong> getInternalMap() {
    return Collections.unmodifiableMap(this.countMap);
}
 
Example 18
Source File: MockResourceRequest.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public Map<String, String[]> getPrivateRenderParameterMap() {
	return Collections.unmodifiableMap(this.privateRenderParameterMap);
}
 
Example 19
Source File: Types.java    From swift-t with Apache License 2.0 4 votes vote down vote up
public static Map<String, Type> getBuiltInTypes() {
  return Collections.unmodifiableMap(nativeTypes);
}
 
Example 20
Source File: BulkCacheWritingException.java    From ehcache3 with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a {@code BulkCacheWritingException} instance with the given map and set.
 * <p>
 * The given arguments are:
 * <ul>
 *   <li>a map from keys to exception thrown while writing,</li>
 *   <li>a set of keys for which writing succeeded</li>
 * </ul>
 *
 * @param failures the map of keys to failure encountered while loading
 * @param successes the map of keys successfully loaded and their associated value
 */
public BulkCacheWritingException(Map<?, Exception> failures, Set<?> successes) {
  this.failures = Collections.unmodifiableMap(failures);
  this.successes = Collections.unmodifiableSet(successes);
}