List of usage examples for java.util OptionalInt of
public static OptionalInt of(int value)
From source file:com.wrmsr.wava.util.collect.MoreMultimaps.java
public static <K, V> Multimap<K, V> unmodifiableMultimapView(Map<K, Collection<V>> collectionMap) { // checkArgument(collectionMap.values().stream().allMatch(coll -> !coll.isEmpty())); return new Multimap<K, V>() { private OptionalInt size = OptionalInt.empty(); private int cachedSize() { if (!size.isPresent()) { size = OptionalInt.of(collectionMap.values().stream().mapToInt(coll -> { checkState(!coll.isEmpty()); return coll.size(); }).sum());/*w ww .ja va 2 s. c o m*/ } return size.getAsInt(); } @Override public int size() { return cachedSize(); } @Override public boolean isEmpty() { return !collectionMap.isEmpty(); } @Override public boolean containsKey(@Nullable Object key) { return collectionMap.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return collectionMap.values().stream().anyMatch(coll -> coll.contains(value)); } @Override public boolean containsEntry(@Nullable Object key, @Nullable Object value) { return collectionMap.getOrDefault(key, ImmutableList.of()).contains(value); } @Override public boolean put(@Nullable K key, @Nullable V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(@Nullable K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } @Override public Collection<V> replaceValues(@Nullable K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public Collection<V> removeAll(@Nullable Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Collection<V> get(@Nullable K key) { return collectionMap.getOrDefault(key, ImmutableList.of()); } @Override public Set<K> keySet() { return collectionMap.keySet(); } @Override public Multiset<K> keys() { // FIXME throw new UnsupportedOperationException(); } @Override public Collection<V> values() { return new AbstractCollection<V>() { @Override public Iterator<V> iterator() { return Iterators.concat(collectionMap.values().stream().map(Iterable::iterator).iterator()); } @Override public int size() { return cachedSize(); } }; } @Override public Collection<Map.Entry<K, V>> entries() { return new AbstractCollection<Map.Entry<K, V>>() { @Override public Iterator<Map.Entry<K, V>> iterator() { return Iterators.concat(collectionMap.entrySet().stream() .map(entry -> entry.getValue().stream() .map(value -> ImmutablePair.of(entry.getKey(), value)).iterator()) .iterator()); } @Override public int size() { return cachedSize(); } }; } @Override public Map<K, Collection<V>> asMap() { return collectionMap; } }; }
From source file:net.minecraftforge.oredict.DyeUtils.java
/** * Get the dye damage from the stack, which can be passed into {@link EnumDyeColor#byDyeDamage(int)}. * @param stack the item stack/*from w ww . j av a2 s .c o m*/ * @return an {@link OptionalInt} holding the dye damage for a dye, or an empty {@link OptionalInt} otherwise */ public static OptionalInt dyeDamageFromStack(ItemStack stack) { final OptionalInt meta = metaFromStack(stack); return meta.isPresent() ? OptionalInt.of(0xF - meta.getAsInt()) : OptionalInt.empty(); }
From source file:com.addthis.bundle.util.AutoField.java
default OptionalInt getInt(Bundle bundle) { ValueObject valueObject = getValue(bundle); if (valueObject == null) { return OptionalInt.empty(); }//from ww w . ja v a 2 s . c o m return OptionalInt.of(ValueUtil.asNumberOrParse(valueObject).asLong().asNative().intValue()); }
From source file:com.wrmsr.wava.yen.translation.UnitTranslation.java
public static Module translateModule(Name name, YModule module) { YMemory ymemory = module.getMemory(); Memory memory = new Memory(ymemory.getInitial(), ymemory.getMax() >= 0 ? OptionalInt.of(ymemory.getMax()) : OptionalInt.empty(), ymemory .getSegments().stream().map( s -> new Segment(s.getOffset(), s.getData().length == s.getSize() ? s.getData() : Arrays.copyOf(s.getData(), s.getSize()))) .collect(toImmutableList())); Table table = new Table(module.getTable().getNames()); Map<Name, Signature> functionSignatures = ImmutableMap.<Name, Signature>builder() .putAll(module.getFunctions().stream() .map(f -> ImmutablePair.of(f.getName().get(), new Signature(f.getResult(), f.getParams()))) .collect(toImmutableList())) .putAll(module.getImports().stream() .map(i -> ImmutablePair.of(i.getName().get(), new Signature(i.getType().getResult(), i.getType().getParams()))) .collect(toImmutableList())) .build();//from w w w.j a v a 2 s.c o m Map<Name, Import> imports = module.getImports().stream() .map(i -> ImmutablePair.of(i.getName().get(), new Import(i.getName().get(), i.getModule(), i.getBase(), new Signature(i.getType().getResult(), i.getType().getParams())))) .collect(toImmutableMap()); Map<Name, Export> exports = module.getExports().stream() .map(e -> ImmutablePair.of(e.getName().get(), new Export(e.getName().get(), e.getValue()))) .collect(toImmutableMap()); Map<Name, Function> functions = module.getFunctions().stream().parallel() // FIXME boo this man .map(f -> ImmutablePair.of(f.getName().get(), translateFunction(f, functionSignatures))) .sequential().collect(toImmutableMap()); Set<Signature> declaredSignatures = module.getNamedFunctionTypes().stream() .map(i -> new Signature(i.getResult(), i.getParams())).collect(Collectors.toSet()); return new Module(name, memory, table, declaredSignatures, imports, exports, functions); }
From source file:com.wrmsr.wava.basic.Basics.java
public static Map<Name, Basic> buildBasics(ControlFlowGraph cfg, ValueTypeAnalysis vta, Map<Node, Name> nodeNames, Map<Node, Integer> nodeIndices) { Map<Name, Basic> map = new LinkedHashMap<>(); acceptRecursive((rec, node) -> {/*w w w.ja v a2 s . c o m*/ Name name; if (node == ControlFlowGraph.ENTRY) { name = ENTRY_NAME; } else { name = requireNonNull(nodeNames.get(node)); checkState(!map.containsKey(name)); checkState(!vta.get(node).isUsed()); } map.put(name, node.accept(new Visitor<Void, Basic>() { private BreakTable newFlowBreakTable(Node node) { return newBreakTable(nodeNames.get(getOnlyElement(cfg.getOutput(node)).getOutput())); } private BreakTable newBreakTable(Name target) { return new BreakTable(ImmutableList.of(), target, new Nop()); } private Basic newBasic(List<Node> body, BreakTable breakTable) { return new Basic(name, body, breakTable, OptionalInt.of(nodeIndices.get(node))); } @Override protected Basic visitNode(Node node, Void context) { return newBasic(ImmutableList.of(node), newFlowBreakTable(node)); } @Override public Basic visitBlock(Block node, Void context) { return newBasic(ImmutableList.of(), newFlowBreakTable(node)); } @Override public Basic visitBreak(Break node, Void context) { checkState(node.getValue() instanceof Nop); return newBasic(ImmutableList.of(), newBreakTable(node.getTarget())); } @Override public Basic visitBreakTable(BreakTable node, Void context) { return newBasic(ImmutableList.of(), node); } @Override public Basic visitIf(If node, Void context) { return newBasic(ImmutableList.of(), new BreakTable(ImmutableList.of(nodeNames.get(node.getIfFalse())), nodeNames.get(node.getIfTrue()), node.getCondition())); } @Override public Basic visitLoop(Loop node, Void context) { return new Basic(name, ImmutableList.of(), newFlowBreakTable(node), OptionalInt.of(nodeIndices.get(node))); } @Override public Basic visitNop(Nop node, Void context) { if (node == ControlFlowGraph.ENTRY) { return new Basic(ENTRY_NAME, ImmutableList.of(), newFlowBreakTable(node), OptionalInt.of(0)); } else { return visitNode(node, context); } } @Override public Basic visitReturn(Return node, Void context) { return newBasic(ImmutableList.of(node), newBreakTable(EXIT_NAME)); } @Override public Basic visitSwitch(Switch node, Void context) { throw new IllegalStateException(); } @Override public Basic visitUnreachable(Unreachable node, Void context) { return newBasic(ImmutableList.of(node), newBreakTable(UNREACHABLE_NAME)); } }, null)); cfg.getOutput(node).stream().map(ControlFlowGraph.Edge::getOutput) .filter(n -> !map.containsKey(nodeNames.get(n))).forEach(rec); }, ControlFlowGraph.ENTRY); return unmodifiableMap(map); }
From source file:cito.stomp.Frame.java
/** * /*from w w w.ja v a 2 s . c o m*/ * @param header * @return */ public OptionalInt getFirstInt(@Nonnull Header header) { final Optional<String> value = getFirst(header); return value.isPresent() ? OptionalInt.of(Integer.parseInt(value.get())) : OptionalInt.empty(); }
From source file:ffx.potential.extended.ExtUtils.java
/** * Parse system properties of type String, Boolean, Integer, Double, OptionalInt, and OptionalDouble. * Default value determines the return type. Provides case-insensitivity in property keys. *//*from www. j a v a 2 s . com*/ @SuppressWarnings("unchecked") public static final <T> T prop(String key, T defaultVal) throws NoSuchElementException, NumberFormatException { if (defaultVal == null) { throw new IllegalArgumentException(); } T parsed = null; try { if (System.getProperty(key) == null) { if (System.getProperty(key.toLowerCase()) != null) { key = key.toLowerCase(); } else if (System.getProperty(key.toUpperCase()) != null) { key = key.toUpperCase(); } else { boolean found = false; for (Object search : System.getProperties().keySet()) { if (search instanceof String && ((String) search).equalsIgnoreCase(key)) { key = (String) search; } } if (!found) { return defaultVal; } } } if (defaultVal instanceof String) { parsed = (System.getProperty(key) != null) ? (T) System.getProperty(key) : defaultVal; } else if (defaultVal instanceof Integer) { return (System.getProperty(key) != null) ? (T) Integer.valueOf(System.getProperty(key)) : defaultVal; } else if (defaultVal instanceof OptionalInt) { parsed = (System.getProperty(key) != null) ? (T) OptionalInt.of(Integer.parseInt(System.getProperty(key))) : defaultVal; } else if (defaultVal instanceof Double) { parsed = (System.getProperty(key) != null) ? (T) Double.valueOf(System.getProperty(key)) : defaultVal; } else if (defaultVal instanceof OptionalDouble) { parsed = (System.getProperty(key) != null) ? (T) OptionalDouble.of(Double.parseDouble(System.getProperty(key))) : defaultVal; } else if (defaultVal instanceof Boolean) { if (System.getProperty(key) != null) { if (System.getProperty(key).isEmpty()) { System.setProperty(key, "true"); } parsed = (T) Boolean.valueOf(System.getProperty(key)); } } else { throw new IllegalArgumentException(); } } catch (IllegalArgumentException ex) { String value = (System.getProperty(key) != null) ? System.getProperty(key) : "null"; logger.warning(String.format("Error parsing property %s with value %s; the default is %s.", key, value, defaultVal.toString())); throw ex; } config.addProperty(key, parsed); return parsed; }
From source file:de.siegmar.securetransfer.controller.SendController.java
private List<SecretFile> handleStream(final HttpServletRequest req, final KeyIv encryptionKey, final DataBinder binder) throws FileUploadException, IOException { final BindingResult errors = binder.getBindingResult(); final MutablePropertyValues propertyValues = new MutablePropertyValues(); final List<SecretFile> tmpFiles = new ArrayList<>(); @SuppressWarnings("checkstyle:anoninnerlength") final AbstractMultipartVisitor visitor = new AbstractMultipartVisitor() { private OptionalInt expiration = OptionalInt.empty(); @Override// w ww . j av a 2s . co m void emitField(final String name, final String value) { propertyValues.addPropertyValue(name, value); if ("expirationDays".equals(name)) { expiration = OptionalInt.of(Integer.parseInt(value)); } } @Override void emitFile(final String fileName, final InputStream inStream) { final Integer expirationDays = expiration .orElseThrow(() -> new IllegalStateException("No expirationDays configured")); tmpFiles.add(messageService.encryptFile(fileName, inStream, encryptionKey, Instant.now().plus(expirationDays, ChronoUnit.DAYS))); } }; try { visitor.processRequest(req); binder.bind(propertyValues); binder.validate(); } catch (final IllegalStateException ise) { errors.reject(null, ise.getMessage()); } return tmpFiles; }
From source file:com.spankingrpgs.model.characters.GameCharacter.java
/** * Returns the level at which this character knows the specified skill, or an empty Optional if the character * does not know the skill./*from ww w .j a v a 2 s. com*/ * * @param skill The skill whose level is desired * * @return The level at which this character knows the skill, or nothing if the character doesn't know the skill */ @JsonIgnore public OptionalInt getSkillLevel(Skill skill) { return knowsSkill(skill) ? OptionalInt.of(skills.get(skill.getName())) : OptionalInt.empty(); }
From source file:nl.salp.warcraft4j.fileformat.dbc.DbcFile.java
/** * Get the ID of an entry at a specific index. * * @param index The index of the entry (counting from 0). * * @return Optional of the id of the entry or empty when no entry was available at the given index. * * @throws DbcParsingException When parsing of the entry failed. *///from w w w .ja v a 2 s. c o m public OptionalInt getEntryId(int index) throws DbcParsingException { OptionalInt id; DbcHeader header = getHeader(); if (index < 0 || index >= header.getEntryCount()) { id = OptionalInt.empty(); } else { try (DataReader reader = getDataReader()) { id = OptionalInt.of(getEntryId(index, reader)); } catch (IOException e) { throw new DbcParsingException( format("Error parsing entry id %d for DBC file %d (%s)", index, filenameHash, filename), e); } } return id; }