Java Code Examples for java.util.Optional#orElse()

The following examples show how to use java.util.Optional#orElse() . 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: UserUtil.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
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));
      }
    }
  }
}
 
Example 2
Source File: GuiUtils.java    From Guilds with MIT License 6 votes vote down vote up
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();
}
 
Example 3
Source File: DefaultAuditUtility.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example 4
Source File: CassandraStorage.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source File: ExtraArtifactsHandler.java    From thorntail with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 6
Source File: LocalProfileComponent.java    From amidst with GNU General Public License v3.0 5 votes vote down vote up
@CalledOnlyBy(AmidstThread.EDT)
private void resolveFinished(Optional<LauncherProfile> launcherProfile) {
	isResolving = false;
	failedResolving = !launcherProfile.isPresent();
	resolvedProfile = launcherProfile.orElse(null);
	repaintComponent();
}
 
Example 7
Source File: WherePredicateStep.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 8
Source File: GlobalData.java    From UltimateCore with MIT License 5 votes vote down vote up
/**
 * 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();
}
 
Example 9
Source File: BatchingPluginSink.java    From ffwd with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 10
Source File: AvroFactory.java    From flink with Apache License 2.0 5 votes vote down vote up
@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)
	);
}
 
Example 11
Source File: AvroFactory.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@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)
	);
}
 
Example 12
Source File: DisplayUtil.java    From jetbrains-plugin-graph-database-support with Apache License 2.0 5 votes vote down vote up
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()));
}
 
Example 13
Source File: AppleBundle.java    From buck with Apache License 2.0 4 votes vote down vote up
public static String getBinaryName(BuildTarget buildTarget, Optional<String> productName) {
  return productName.orElse(buildTarget.getShortName());
}
 
Example 14
Source File: SerializableQuotaLimitValue.java    From james-project with Apache License 2.0 4 votes vote down vote up
public static <U extends QuotaLimitValue<U>> SerializableQuotaLimitValue<U> valueOf(Optional<U> input) {
    return new SerializableQuotaLimitValue<>(input.orElse(null));
}
 
Example 15
Source File: OptionalHeaderParamResourceTest.java    From dropwizard-java8 with Apache License 2.0 4 votes vote down vote up
@GET
@Path("/message")
public String getMessage(@HeaderParam("message") Optional<String> message) {
    return message.orElse("Default Message");
}
 
Example 16
Source File: OperationLimitsNode.java    From ua-server-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public UInteger getMaxNodesPerNodeManagement() {
    Optional<UInteger> property = getProperty(OperationLimitsType.MAX_NODES_PER_NODE_MANAGEMENT);

    return property.orElse(null);
}
 
Example 17
Source File: OptionalFormParamResourceTest.java    From dropwizard-java8 with Apache License 2.0 4 votes vote down vote up
@POST
@Path("/message")
public String getMessage(@FormParam("message") Optional<String> message) {
    return message.orElse("Default Message");
}
 
Example 18
Source File: CredentialProviderRegistry.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static String determineProviderFrom(final Connector connector) {
    final Optional<String> authentication = connector.propertyTaggedWith(Credentials.AUTHENTICATION_TYPE_TAG);

    return authentication.orElse(connector.getId().get());
}
 
Example 19
Source File: JobResourceAdapter.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
protected JobResourceAdapter<T> loadResource(Long id, ApplicationContext context) {
    Optional<T> resource = find(id, context);
    this.resource = resource.orElse(null);
    return this;
}
 
Example 20
Source File: NamespaceMetadataNode.java    From ua-server-sdk with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public DateTime getNamespacePublicationDate() {
    Optional<DateTime> property = getProperty(NamespaceMetadataType.NAMESPACE_PUBLICATION_DATE);

    return property.orElse(null);
}