下面列出了java.util.Optional#orElse ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Collection<RepairRun> getRepairRunsForCluster(String clusterName, Optional<Integer> limit) {
List<ResultSetFuture> repairRunFutures = Lists.<ResultSetFuture>newArrayList();
// Grab all ids for the given cluster name
Collection<UUID> repairRunIds = getRepairRunIdsForCluster(clusterName);
// Grab repair runs asynchronously for all the ids returned by the index table
for (UUID repairRunId : repairRunIds) {
repairRunFutures.add(session.executeAsync(getRepairRunPrepStmt.bind(repairRunId)));
if (repairRunFutures.size() == limit.orElse(1000)) {
break;
}
}
return getRepairRunsAsync(repairRunFutures);
}
@Override
@Transactional
public void setAuditEntrySuccess(Collection<Long> auditEntryIds) {
for (Long auditEntryId : auditEntryIds) {
try {
Optional<AuditEntryEntity> auditEntryEntityOptional = auditEntryRepository.findById(auditEntryId);
if (auditEntryEntityOptional.isEmpty()) {
logger.error("Could not find the audit entry {} to set the success status.", auditEntryId);
}
AuditEntryEntity auditEntryEntity = auditEntryEntityOptional.orElse(new AuditEntryEntity());
auditEntryEntity.setStatus(AuditEntryStatus.SUCCESS.toString());
auditEntryEntity.setErrorMessage(null);
auditEntryEntity.setErrorStackTrace(null);
auditEntryEntity.setTimeLastSent(DateUtils.createCurrentDateTimestamp());
auditEntryRepository.save(auditEntryEntity);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}
public static ItemStack createItem(String material, String name, List<String> lore) {
Optional<XMaterial> tempMaterial = XMaterial.matchXMaterial(material);
XMaterial tempCheck = tempMaterial.orElse(XMaterial.GLASS_PANE);
ItemStack item = tempCheck.parseItem();
if (item == null) {
item = XMaterial.GLASS_PANE.parseItem();
}
// Extra check
if (problemItems.contains(item.getType())) {
LoggingUtils.warn("Problematic Material Type Found! Switching to Barrier.");
item.setType(XMaterial.BARRIER.parseMaterial());
}
ItemBuilder builder = new ItemBuilder(item);
builder.setName(StringUtils.color(name));
if (!lore.isEmpty()) {
builder.setLore(lore.stream().map(StringUtils ::color).collect(Collectors.toList()));
}
builder.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
return builder.build();
}
public static void validateUserExternalIds(User user) {
List<Map<String, String>> dbResExternalIds = getUserExternalIds(user.getUserId());
List<Map<String, String>> externalIds = user.getExternalIds();
if (CollectionUtils.isNotEmpty(externalIds)) {
for (Map<String, String> extIdMap : externalIds) {
Optional<Map<String, String>> extMap = checkExternalID(dbResExternalIds, extIdMap);
Map<String, String> map = extMap.orElse(null);
// Allowed operation type for externalIds ("add", "remove", "edit")
if (!(JsonKey.ADD.equalsIgnoreCase(extIdMap.get(JsonKey.OPERATION))
|| StringUtils.isBlank(extIdMap.get(JsonKey.OPERATION)))
&& MapUtils.isEmpty(map)) {
// operation is either edit or remove
throwExternalIDNotFoundException(
extIdMap.get(JsonKey.ID),
extIdMap.get(JsonKey.ID_TYPE),
extIdMap.get(JsonKey.PROVIDER));
}
}
}
}
private DependencyNode createNode(DependencyNode n, Optional<String> extension, Optional<String> classifier) {
Artifact original = n.getArtifact();
Artifact withExtension =
new DefaultArtifact(original.getGroupId(),
original.getArtifactId(),
classifier.orElse(original.getClassifier()),
extension.orElse(original.getExtension()),
original.getVersion(),
original.getProperties(),
(File) null);
DefaultDependencyNode nodeWithClassifier = new DefaultDependencyNode(new Dependency(withExtension, "system"));
return nodeWithClassifier;
}
public static String getProperty(GraphNode node) {
Optional<String> backup = Optional.empty();
Optional<String> fuzzyMatch = Optional.empty();
for (Map.Entry<String, Object> entry : node.getPropertyContainer().getProperties().entrySet()) {
Object valueObj = entry.getValue();
if (valueObj instanceof String) {
String key = entry.getKey();
String value = (String) valueObj;
for (String titleIndicator : TITLE_INDICATORS) {
if (titleIndicator.equals(key) && filterLength(value)) {
return value;
}
if (key.contains(titleIndicator) && !fuzzyMatch.isPresent()) {
fuzzyMatch = Optional.of(value)
.filter(DisplayUtil::filterLength);
}
}
if (!backup.isPresent()) {
backup = Optional.of(value)
.filter(DisplayUtil::filterLength);
}
}
}
return fuzzyMatch.orElse(backup.orElse(node.getId()));
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private static <T> AvroFactory<T> fromSpecific(Class<T> type, ClassLoader cl, Optional<Schema> previousSchema) {
SpecificData specificData = new SpecificData(cl);
Schema newSchema = specificData.getSchema(type);
return new AvroFactory<>(
specificData,
newSchema,
new SpecificDatumReader<>(previousSchema.orElse(newSchema), newSchema, specificData),
new SpecificDatumWriter<>(newSchema, specificData)
);
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
private static <T> AvroFactory<T> fromReflective(Class<T> type, ClassLoader cl, Optional<Schema> previousSchema) {
ReflectData reflectData = new ReflectData(cl);
Schema newSchema = reflectData.getSchema(type);
return new AvroFactory<>(
reflectData,
newSchema,
new ReflectDatumReader<>(previousSchema.orElse(newSchema), newSchema, reflectData),
new ReflectDatumWriter<>(newSchema, reflectData)
);
}
public BatchingPluginSink(
final long flushInterval, final Optional<Long> batchSizeLimit,
final Optional<Long> maxPendingFlushes
) {
this(flushInterval, batchSizeLimit.orElse(DEFAULT_BATCH_SIZE_LIMIT),
maxPendingFlushes.orElse(DEFAULT_MAX_PENDING_FLUSHES));
}
/**
* Get the value for the provided key, or {@link Optional#empty()} when no value was found in the map.
*
* @param key The key to search for
* @param <C> The expected type of value to be returned
* @return The value found, or {@link Optional#empty()} when no value was found.
*/
public static <C> Optional<C> getRaw(Key.Global<C> key) {
Optional<C> rtrn;
if (!datas.containsKey(key.getIdentifier())) {
rtrn = Optional.empty();
} else {
rtrn = Optional.ofNullable((C) datas.get(key.getIdentifier()));
}
DataRetrieveEvent<C> event = new DataRetrieveEvent<>(key, rtrn.orElse(null), Cause.builder().append(UltimateCore.getContainer()).build(EventContext.builder().build()));
Sponge.getEventManager().post(event);
return event.getValue();
}
public WherePredicateStep(final Traversal.Admin traversal, final Optional<String> startKey, final P<String> predicate) {
super(traversal);
this.startKey = startKey.orElse(null);
if (null != this.startKey)
this.scopeKeys.add(this.startKey);
this.predicate = (P) predicate;
this.selectKeys = new ArrayList<>();
this.configurePredicates(this.predicate);
}
@CalledOnlyBy(AmidstThread.EDT)
private void resolveFinished(Optional<LauncherProfile> launcherProfile) {
isResolving = false;
failedResolving = !launcherProfile.isPresent();
resolvedProfile = launcherProfile.orElse(null);
repaintComponent();
}
@Override
public DateTime getNamespacePublicationDate() {
Optional<DateTime> property = getProperty(NamespaceMetadataType.NAMESPACE_PUBLICATION_DATE);
return property.orElse(null);
}
public static String getBinaryName(BuildTarget buildTarget, Optional<String> productName) {
return productName.orElse(buildTarget.getShortName());
}
public static <U extends QuotaLimitValue<U>> SerializableQuotaLimitValue<U> valueOf(Optional<U> input) {
return new SerializableQuotaLimitValue<>(input.orElse(null));
}
@GET
@Path("/message")
public String getMessage(@HeaderParam("message") Optional<String> message) {
return message.orElse("Default Message");
}
@Override
public UInteger getMaxNodesPerNodeManagement() {
Optional<UInteger> property = getProperty(OperationLimitsType.MAX_NODES_PER_NODE_MANAGEMENT);
return property.orElse(null);
}
@POST
@Path("/message")
public String getMessage(@FormParam("message") Optional<String> message) {
return message.orElse("Default Message");
}
private static String determineProviderFrom(final Connector connector) {
final Optional<String> authentication = connector.propertyTaggedWith(Credentials.AUTHENTICATION_TYPE_TAG);
return authentication.orElse(connector.getId().get());
}
protected JobResourceAdapter<T> loadResource(Long id, ApplicationContext context) {
Optional<T> resource = find(id, context);
this.resource = resource.orElse(null);
return this;
}