下面列出了com.google.common.collect.Maps#newEnumMap ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 读取二维码图片
*
* @param path
* @return
* @throws Exception
*/
public static String read(String path) throws Exception {
File file = new File(path);
BufferedImage image;
image = ImageIO.read(file);
if (Objects.isNull(image)) {
throw new RuntimeException("无法读取源文件");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
@SuppressWarnings("rawtypes")
EnumMap<DecodeHintType, String> hints = Maps.newEnumMap(DecodeHintType.class);
//解码设置编码方式为:utf-8
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
/**
* 根据内容生成二维码数据
*
* @param content 二维码文字内容[为了信息安全性,一般都要先进行数据加密]
* @param length 二维码图片宽度和高度
*/
private static BitMatrix createQrcodeMatrix(String content, int length) {
Map<EncodeHintType, Object> hints = Maps.newEnumMap(EncodeHintType.class);
// 设置字符编码
hints.put(EncodeHintType.CHARACTER_SET, Charsets.UTF_8.name());
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
try {
return new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, length, length, hints);
} catch (Exception e) {
logger.warn("内容为:【" + content + "】的二维码生成失败!", e);
return null;
}
}
@EventHandler(priority = EventPriority.LOW)
public void on(PlayerDeathEvent event) {
if (!isEnabled() || RANDOM.nextDouble() < (1D - dropRate)) {
// set to an empty map to avoid stale metadata problems
event.getEntity().setMetadata(StandItemsMetadata.KEY, new StandItemsMetadata(plugin));
return;
}
final Player player = event.getEntity();
// create a head
final ItemStack head = playerHeadProvider.getPlayerHeadItem(player);
// add it to the drops
event.getDrops().add(head);
// add metadata for the armour stand module to put the helmet on the player and remove from drops
final EnumMap<EquipmentSlot, ItemStack> standItems = Maps.newEnumMap(EquipmentSlot.class);
standItems.put(EquipmentSlot.HEAD, head);
player.setMetadata(StandItemsMetadata.KEY, new StandItemsMetadata(plugin, standItems));
}
/**
* For a given Enum type, creates an immutable map from each of the Enum's values to a
* corresponding LockGraphNode, with the {@code allowedPriorLocks} and
* {@code disallowedPriorLocks} prepopulated with nodes according to the natural ordering of the
* associated Enum values.
*/
@VisibleForTesting
static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) {
EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz);
E[] keys = clazz.getEnumConstants();
final int numKeys = keys.length;
ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys);
// Create a LockGraphNode for each enum value.
for (E key : keys) {
LockGraphNode node = new LockGraphNode(getLockName(key));
nodes.add(node);
map.put(key, node);
}
// Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
for (int i = 1; i < numKeys; i++) {
nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
}
// Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
for (int i = 0; i < numKeys - 1; i++) {
nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
}
return Collections.unmodifiableMap(map);
}
/**
* For a given Enum type, creates an immutable map from each of the Enum's values to a
* corresponding LockGraphNode, with the {@code allowedPriorLocks} and
* {@code disallowedPriorLocks} prepopulated with nodes according to the natural ordering of the
* associated Enum values.
*/
@VisibleForTesting
static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) {
EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz);
E[] keys = clazz.getEnumConstants();
final int numKeys = keys.length;
ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys);
// Create a LockGraphNode for each enum value.
for (E key : keys) {
LockGraphNode node = new LockGraphNode(getLockName(key));
nodes.add(node);
map.put(key, node);
}
// Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
for (int i = 1; i < numKeys; i++) {
nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
}
// Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
for (int i = 0; i < numKeys - 1; i++) {
nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
}
return Collections.unmodifiableMap(map);
}
private Map<Side, Vec3d> calculateHitPoints(Vec3d near, Vec3d far) {
Vec3d diff = far.subtract(near);
Map<Side, Vec3d> result = Maps.newEnumMap(Side.class);
addPoint(result, Side.XNeg, calculateXPoint(near, diff, negX));
addPoint(result, Side.XPos, calculateXPoint(near, diff, posX));
addPoint(result, Side.YNeg, calculateYPoint(near, diff, negY));
addPoint(result, Side.YPos, calculateYPoint(near, diff, posY));
addPoint(result, Side.ZNeg, calculateZPoint(near, diff, negZ));
addPoint(result, Side.ZPos, calculateZPoint(near, diff, posZ));
return result;
}
@Override
public void beforeCheckProject(@NonNull Context context) {
// In incremental mode, or checking all files (full lint analysis) ? If the latter,
// we should store state and look for deeper cycles
if (context.getScope().contains(Scope.ALL_RESOURCE_FILES)) {
mReferences = Maps.newEnumMap(ResourceType.class);
}
}
/**
* Generates the default mapping of included paths from the given {@code qualifier} and {@code type}.
*
* @param qualifier the prefix to add to the initial resource path
* @param type the type of data to include
*
* @return the map of included paths
*/
protected Map<MetaInfGroup, String> getDefaultIncludes(String qualifier, MetaInfDataType type) {
Map<MetaInfGroup, String> defaultIncludes = Maps.newEnumMap(MetaInfGroup.class);
String resourcePath = ProjectUtils.getResourcePath(project.getGroupId(), project.getArtifactId());
List<String> paths = Lists.newArrayList(resourcePath, qualifier, type.name().toLowerCase(), ALL_XML_PATH);
defaultIncludes.put(MetaInfGroup.OTHER, StringUtils.join(paths, PATH_SEPARATOR));
return defaultIncludes;
}
@Override
public void beforeCheckFile(@NonNull Context context) {
File parent = context.file.getParentFile();
if (!parent.equals(mParent)) {
mParent = parent;
mTypeMap = Maps.newEnumMap(ResourceType.class);
mLocations = Maps.newEnumMap(ResourceType.class);
}
}
protected EnumMap<EquipmentSlot, ItemStack> getSavedSlots(Player player) {
for (final MetadataValue value : player.getMetadata(StandItemsMetadata.KEY)) {
if (!(value instanceof StandItemsMetadata)) continue;
// remove the metadata
player.removeMetadata(StandItemsMetadata.KEY, value.getOwningPlugin());
// return the map
return ((StandItemsMetadata) value).value();
}
return Maps.newEnumMap(EquipmentSlot.class);
}
/**
* Filters (discards) any existing ACL entries that have the same scope, type
* and name of any entry in the ACL spec. If necessary, recalculates the mask
* entries. If necessary, default entries may be inferred by copying the
* permissions of the corresponding access entries. It is invalid to request
* removal of the mask entry from an ACL that would otherwise require a mask
* entry, due to existing named entries or an unnamed group entry.
*
* @param existingAcl List<AclEntry> existing ACL
* @param inAclSpec List<AclEntry> ACL spec describing entries to filter
* @return List<AclEntry> new ACL
* @throws AclException if validation fails
*/
public static List<AclEntry> filterAclEntriesByAclSpec(
List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry> providedMask =
Maps.newEnumMap(AclEntryScope.class);
EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class);
EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class);
for (AclEntry existingEntry: existingAcl) {
if (aclSpec.containsKey(existingEntry)) {
scopeDirty.add(existingEntry.getScope());
if (existingEntry.getType() == MASK) {
maskDirty.add(existingEntry.getScope());
}
} else {
if (existingEntry.getType() == MASK) {
providedMask.put(existingEntry.getScope(), existingEntry);
} else {
aclBuilder.add(existingEntry);
}
}
}
copyDefaultsIfNeeded(aclBuilder);
calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty);
return buildAndValidateAcl(aclBuilder);
}
/** Similar to {@code scrapeStringNodes}, but for string array nodes. */
@VisibleForTesting
void scrapeStringArrayNodes(
NodeList arrayNodes, Map<Integer, EnumMap<Gender, ImmutableList<String>>> arraysMap) {
for (int i = 0; i < arrayNodes.getLength(); ++i) {
Element element = (Element) arrayNodes.item(i);
String resourceName = element.getAttribute("name");
Gender gender = getGender(element);
Integer resourceId = getResourceId(resourceName, gender, arrayResourceNameToIdMap);
// Ignore a resource if R.txt does not contain an entry for it.
if (resourceId == null) {
continue;
}
EnumMap<Gender, ImmutableList<String>> genderMap = arraysMap.get(resourceId);
if (genderMap == null) {
genderMap = Maps.newEnumMap(Gender.class);
} else if (genderMap.containsKey(gender)) { // Ignore a resource if it has already been found
continue;
}
ImmutableList.Builder<String> arrayValues = ImmutableList.builder();
NodeList itemNodes = element.getElementsByTagName("item");
if (itemNodes.getLength() == 0) {
continue;
}
for (int j = 0; j < itemNodes.getLength(); ++j) {
arrayValues.add(itemNodes.item(j).getTextContent());
}
genderMap.put(gender, arrayValues.build());
arraysMap.put(resourceId, genderMap);
}
}
/**
* Filters (discards) any existing ACL entries that have the same scope, type
* and name of any entry in the ACL spec. If necessary, recalculates the mask
* entries. If necessary, default entries may be inferred by copying the
* permissions of the corresponding access entries. It is invalid to request
* removal of the mask entry from an ACL that would otherwise require a mask
* entry, due to existing named entries or an unnamed group entry.
*
* @param existingAcl List<AclEntry> existing ACL
* @param inAclSpec List<AclEntry> ACL spec describing entries to filter
* @return List<AclEntry> new ACL
* @throws AclException if validation fails
*/
public static List<AclEntry> filterAclEntriesByAclSpec(
List<AclEntry> existingAcl, List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
EnumMap<AclEntryScope, AclEntry> providedMask =
Maps.newEnumMap(AclEntryScope.class);
EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class);
EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class);
for (AclEntry existingEntry: existingAcl) {
if (aclSpec.containsKey(existingEntry)) {
scopeDirty.add(existingEntry.getScope());
if (existingEntry.getType() == MASK) {
maskDirty.add(existingEntry.getScope());
}
} else {
if (existingEntry.getType() == MASK) {
providedMask.put(existingEntry.getScope(), existingEntry);
} else {
aclBuilder.add(existingEntry);
}
}
}
copyDefaultsIfNeeded(aclBuilder);
calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty);
return buildAndValidateAcl(aclBuilder);
}
/**
* Completely replaces the ACL with the entries of the ACL spec. If
* necessary, recalculates the mask entries. If necessary, default entries
* are inferred by copying the permissions of the corresponding access
* entries. Replacement occurs separately for each of the access ACL and the
* default ACL. If the ACL spec contains only access entries, then the
* existing default entries are retained. If the ACL spec contains only
* default entries, then the existing access entries are retained. If the ACL
* spec contains both access and default entries, then both are replaced.
*
* @param existingAcl List<AclEntry> existing ACL
* @param inAclSpec List<AclEntry> ACL spec containing replacement entries
* @return List<AclEntry> new ACL
* @throws AclException if validation fails
*/
public static List<AclEntry> replaceAclEntries(List<AclEntry> existingAcl,
List<AclEntry> inAclSpec) throws AclException {
ValidatedAclSpec aclSpec = new ValidatedAclSpec(inAclSpec);
ArrayList<AclEntry> aclBuilder = Lists.newArrayListWithCapacity(MAX_ENTRIES);
// Replacement is done separately for each scope: access and default.
EnumMap<AclEntryScope, AclEntry> providedMask =
Maps.newEnumMap(AclEntryScope.class);
EnumSet<AclEntryScope> maskDirty = EnumSet.noneOf(AclEntryScope.class);
EnumSet<AclEntryScope> scopeDirty = EnumSet.noneOf(AclEntryScope.class);
for (AclEntry aclSpecEntry: aclSpec) {
scopeDirty.add(aclSpecEntry.getScope());
if (aclSpecEntry.getType() == MASK) {
providedMask.put(aclSpecEntry.getScope(), aclSpecEntry);
maskDirty.add(aclSpecEntry.getScope());
} else {
aclBuilder.add(aclSpecEntry);
}
}
// Copy existing entries if the scope was not replaced.
for (AclEntry existingEntry: existingAcl) {
if (!scopeDirty.contains(existingEntry.getScope())) {
if (existingEntry.getType() == MASK) {
providedMask.put(existingEntry.getScope(), existingEntry);
} else {
aclBuilder.add(existingEntry);
}
}
}
copyDefaultsIfNeeded(aclBuilder);
calculateMasks(aclBuilder, providedMask, maskDirty, scopeDirty);
return buildAndValidateAcl(aclBuilder);
}
/**
* Parses the file and returns a list of {@link ResourceItem} objects.
* @return a list of resources.
*
* @throws MergingException if a merging exception happens
*/
@NonNull
List<ResourceItem> parseFile() throws MergingException {
Document document = parseDocument(mFile);
// get the root node
Node rootNode = document.getDocumentElement();
if (rootNode == null) {
return Collections.emptyList();
}
NodeList nodes = rootNode.getChildNodes();
final int count = nodes.getLength();
// list containing the result
List<ResourceItem> resources = Lists.newArrayListWithExpectedSize(count);
// Multimap to detect dups
Map<ResourceType, Set<String>> map = Maps.newEnumMap(ResourceType.class);
for (int i = 0, n = nodes.getLength(); i < n; i++) {
Node node = nodes.item(i);
if (node.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
ResourceItem resource = getResource(node, mFile);
if (resource != null) {
// check this is not a dup
checkDuplicate(resource, map);
resources.add(resource);
if (resource.getType() == ResourceType.DECLARE_STYLEABLE) {
// Need to also create ATTR items for its children
try {
addStyleableItems(node, resources, map, mFile);
} catch (MergingException e) {
e.setFile(mFile);
throw e;
}
}
}
}
return resources;
}
public GuiCapture(long guid) {
this.guid = guid;
this.originalState = GuiUtils.storeGuiElementsState();
this.updatedState = Maps.newEnumMap(GuiElements.class);
}
@Test
public void testScrapeStringNodes() throws IOException, SAXException {
String xmlInput =
"<string name='name1' gender='unknown'>Value1</string>"
+ "<string name='name1_f1gender' gender='female'>Value1_f1</string>"
+ "<string name='name2' gender='unknown'>Value with space</string>"
+ "<string name='name2_m2gender' gender='male'>Value with space m2</string>"
+ "<string name='name3' gender='unknown'>Value with \"quotes\"</string>"
+ "<string name='name4' gender='unknown'></string>"
+
// ignored because "name3" already found
"<string name='name3' gender='unknown'>IGNORE</string>"
+ "<string name='name5' gender='unknown'>Value with %1$s</string>";
NodeList stringNodes =
XmlDomParser.parse(createResourcesXml(xmlInput)).getElementsByTagName("string");
EnumMap<Gender, String> map1 = Maps.newEnumMap(Gender.class);
map1.put(Gender.unknown, "Value1");
map1.put(Gender.female, "Value1_f1");
EnumMap<Gender, String> map2 = Maps.newEnumMap(Gender.class);
map2.put(Gender.unknown, "Value with space");
map2.put(Gender.male, "Value with space m2");
EnumMap<Gender, String> map3 = Maps.newEnumMap(Gender.class);
map3.put(Gender.unknown, "Value with \"quotes\"");
EnumMap<Gender, String> map4 = Maps.newEnumMap(Gender.class);
map4.put(Gender.unknown, "");
EnumMap<Gender, String> map5 = Maps.newEnumMap(Gender.class);
map5.put(Gender.unknown, "Value with %1$s");
Map<Integer, EnumMap<Gender, String>> stringsMap = new HashMap<>();
CompileStringsStep step = createNonExecutingStep();
step.addStringResourceNameToIdMap(
ImmutableMap.of(
"name1", 1,
"name2", 2,
"name3", 3,
"name4", 4,
"name5", 5));
step.scrapeStringNodes(stringNodes, stringsMap);
assertEquals(
"Incorrect map of resource id to string values.",
ImmutableMap.of(
1, map1,
2, map2,
3, map3,
4, map4,
5, map5),
stringsMap);
}
private TrafficTreatment.Builder buildStatTrigger(OFOxsList oxsList,
Set<OFStatTriggerFlags> flagsSet,
TrafficTreatment.Builder builder) {
Map<StatTriggerField, Long> statTriggerMap = Maps.newEnumMap(StatTriggerField.class);
for (OFOxs<?> ofOxs : oxsList) {
switch (ofOxs.getStatField().id) {
case DURATION:
U64 durationType = (U64) ofOxs.getValue();
statTriggerMap.put(DURATION, durationType.getValue());
break;
case FLOW_COUNT:
U32 flowCount = (U32) ofOxs.getValue();
statTriggerMap.put(FLOW_COUNT, flowCount.getValue());
break;
case PACKET_COUNT:
U64 packetCount = (U64) ofOxs.getValue();
statTriggerMap.put(PACKET_COUNT, packetCount.getValue());
break;
case BYTE_COUNT:
U64 byteCount = (U64) ofOxs.getValue();
statTriggerMap.put(BYTE_COUNT, byteCount.getValue());
break;
case IDLE_TIME:
U64 idleTime = (U64) ofOxs.getValue();
statTriggerMap.put(IDLE_TIME, idleTime.getValue());
break;
default:
log.warn("getStatField not supported {}", ofOxs.getStatField().id);
break;
}
}
StatTriggerFlag flag = null;
for (OFStatTriggerFlags flags : flagsSet) {
switch (flags) {
case PERIODIC:
flag = PERIODIC;
break;
case ONLY_FIRST:
flag = ONLY_FIRST;
break;
default:
log.warn("flag not supported {}", flags);
break;
}
}
if (!statTriggerMap.isEmpty() && flag != null) {
builder.add(Instructions.statTrigger(statTriggerMap, flag));
}
return builder;
}
public StandItemsMetadata(Plugin owningPlugin) {
this(owningPlugin, Maps.<EquipmentSlot, ItemStack>newEnumMap(EquipmentSlot.class));
}
@Test
public void testScrapeNodesWithSameName() throws IOException, SAXException {
String xmlInput =
"<string name='name1' gender='unknown'>1</string>"
+ "<string name='name1_f1gender' gender='female'>1 f1</string>"
+ "<plurals name='name1' gender='unknown'>"
+ "<item quantity='one'>2</item>"
+ "<item quantity='other'>3</item>"
+ "</plurals>"
+ "<plurals name='name1_f1gender' gender='female'>"
+ "<item quantity='one'>2 f1</item>"
+ "<item quantity='other'>3 f1</item>"
+ "</plurals>"
+ "<string-array name='name1' gender='unknown'>"
+ "<item>4</item>"
+ "<item>5</item>"
+ "</string-array>"
+ "<string-array name='name1_f1gender' gender='female'>"
+ "<item>4 f1</item>"
+ "<item>5 f1</item>"
+ "</string-array>";
NodeList stringNodes =
XmlDomParser.parse(createResourcesXml(xmlInput)).getElementsByTagName("string");
NodeList pluralsNodes =
XmlDomParser.parse(createResourcesXml(xmlInput)).getElementsByTagName("plurals");
NodeList arrayNodes =
XmlDomParser.parse(createResourcesXml(xmlInput)).getElementsByTagName("string-array");
Map<Integer, EnumMap<Gender, String>> stringMap = new TreeMap<>();
Map<Integer, EnumMap<Gender, ImmutableMap<String, String>>> pluralsMap = new TreeMap<>();
Map<Integer, EnumMap<Gender, ImmutableList<String>>> arraysMap = new TreeMap<>();
EnumMap<Gender, String> map1 = Maps.newEnumMap(Gender.class);
map1.put(Gender.unknown, "1");
map1.put(Gender.female, "1 f1");
EnumMap<Gender, Map<String, String>> map2 = Maps.newEnumMap(Gender.class);
map2.put(Gender.unknown, ImmutableMap.of("one", "2", "other", "3"));
map2.put(Gender.female, ImmutableMap.of("one", "2 f1", "other", "3 f1"));
EnumMap<Gender, ImmutableList<String>> map3 = Maps.newEnumMap(Gender.class);
map3.put(Gender.unknown, ImmutableList.of("4", "5"));
map3.put(Gender.female, ImmutableList.of("4 f1", "5 f1"));
CompileStringsStep step = createNonExecutingStep();
step.addStringResourceNameToIdMap(ImmutableMap.of("name1", 1));
step.addPluralsResourceNameToIdMap(ImmutableMap.of("name1", 2));
step.addArrayResourceNameToIdMap(ImmutableMap.of("name1", 3));
step.scrapeStringNodes(stringNodes, stringMap);
step.scrapePluralsNodes(pluralsNodes, pluralsMap);
step.scrapeStringArrayNodes(arrayNodes, arraysMap);
assertEquals("Incorrect map of resource id to string.", ImmutableMap.of(1, map1), stringMap);
assertEquals("Incorrect map of resource id to plurals.", ImmutableMap.of(2, map2), pluralsMap);
assertEquals(
"Incorrect map of resource id to string arrays.", ImmutableMap.of(3, map3), arraysMap);
}