本文整理匯總了Java中java.util.Optional.isPresent方法的典型用法代碼示例。如果您正苦於以下問題:Java Optional.isPresent方法的具體用法?Java Optional.isPresent怎麽用?Java Optional.isPresent使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.Optional
的用法示例。
在下文中一共展示了Optional.isPresent方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: resolve
import java.util.Optional; //導入方法依賴的package包/類
private void resolve(Route route) {
// Monitor the IP address for updates of the MAC address
hostService.startMonitoringIp(route.nextHop());
MacAddress nextHopMac = routeStore.getNextHop(route.nextHop());
if (nextHopMac == null) {
Set<Host> hosts = hostService.getHostsByIp(route.nextHop());
Optional<Host> host = hosts.stream().findFirst();
if (host.isPresent()) {
nextHopMac = host.get().mac();
}
}
if (nextHopMac != null) {
routeStore.updateNextHop(route.nextHop(), nextHopMac);
}
}
示例2: isElementEnabled
import java.util.Optional; //導入方法依賴的package包/類
@Override
public boolean isElementEnabled(String elementId) {
TestObject object = elements.get(elementId);
Optional<String> enabledMethod = object.getDynamicMethodList().stream().filter(m -> m.equals("Enabled"))
.findFirst();
if (enabledMethod.isPresent()) {
return (boolean) object.getProperty("Enabled");
} else {
try {
Method method = object.getClass().getMethod("isEnabled");
boolean enabled = (boolean) method.invoke(object);
return enabled;
} catch (Exception e) {
throw new RuntimeException(e); // TODO: Better error handling
}
}
}
示例3: loadUserByUsername
import java.util.Optional; //導入方法依賴的package包/類
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<Account> account = accountRepo.findByUsername( s );
if ( account.isPresent() ) {
return account.get();
} else {
throw new UsernameNotFoundException(String.format("Username[%s] not found", s));
}
}
開發者ID:tinmegali,項目名稱:Oauth2-Stateless-Authentication-with-Spring-and-JWT-Token,代碼行數:10,代碼來源:AccountService.java
示例4: getQuery
import java.util.Optional; //導入方法依賴的package包/類
@ApiOperation(value = "update a query based on new slot-assignments", response = Query.class)
@RequestMapping(value = "{id}/query/{template}/{creator}", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getQuery(
AuthContext authContext,
@PathVariable("id") ObjectId id,
@PathVariable("template") int templateIdx,
@PathVariable("creator") String creator,
@ApiParam(hidden = true) @RequestParam(required = false) MultiValueMap<String, String> params,
@RequestBody QueryUpdate queryUpdate
) {
final Conversation conversation = authenticationService.assertConversation(authContext, id);
final Client client = authenticationService.assertClient(authContext, conversation.getOwner());
final Configuration clientConf = configService.getClientConfiguration(client.getId());
if(clientConf == null){
log.info("Client {} of Conversation {} has no longer a configuration assigned ... returning 404 NOT FOUND",
conversation.getChannelId(), conversation.getId());
return ResponseEntity.notFound().build();
}
final Template template = conversation.getTemplates().get(templateIdx);
if (template == null) return ResponseEntity.notFound().build();
//NOTE: conversationService.getConversation(..) already update the queries if necessary
//so at this place we only need to retrieve the requested query
Optional<Query> query = template.getQueries().stream().filter(q -> Objects.equals(creator, q.getCreator())).findFirst();
return query.isPresent() ? ResponseEntity.ok(query.get()) : ResponseEntity.notFound().build();
}
示例5: kafkaListener
import java.util.Optional; //導入方法依賴的package包/類
@KafkaListener(topics = {"inventory"})
public void kafkaListener(ConsumerRecord<?, byte[]> record) {
Optional<?> messages = Optional.ofNullable(record.value());
if (messages.isPresent()) {
byte[] msg = (byte[]) messages.get();
LogUtil.debug(LOGGER, "接收到Myth分布式框架消息對象:{}", () -> msg);
mythMqReceiveService.processMessage(msg);
}
}
示例6: resolveMaps
import java.util.Optional; //導入方法依賴的package包/類
@Override
public List<PGMMap> resolveMaps(List<String> namesOrIds) {
List<PGMMap> mapResult = Lists.newArrayList();
for(String slug : namesOrIds) {
Optional<PGMMap> map = this.getMapByNameOrId(slug);
if(map.isPresent()) {
mapResult.add(map.get());
} else {
this.logger.warning("Could not find map: " + slug);
}
}
return mapResult;
}
示例7: getParticipatingLiveChallenge
import java.util.Optional; //導入方法依賴的package包/類
public Challenge getParticipatingLiveChallenge() {
Optional<Challenge> findFirst = challengeService.findAll().stream()
.filter(e -> e.getIsOpen())
.filter(e -> challengeService.isParticipating(e, userService.getCurrentUser()))
.findFirst();
if (findFirst.isPresent()) {
return findFirst.get();
} else {
return null;
}
}
示例8: getScenario
import java.util.Optional; //導入方法依賴的package包/類
/**
* TODO serhat:
* This service gets all scenarios and filters it. This should change later and agents should
* have an endpoint that provides specific scenario details
*/
public Scenario getScenario(String agentName, String scenarioId) throws IOException, ScenarioDoesNotExist {
final List<Scenario> scenarios = getScenarios(agentName);
final Optional<Scenario> scenarioOptional = scenarios.stream().filter(sc -> sc.getId().equalsIgnoreCase(scenarioId)).findFirst();
if (!scenarioOptional.isPresent()) {
throw new ScenarioDoesNotExist("Scenario '" + scenarioId + "' does not exist.");
}
return scenarioOptional.get();
}
示例9: createResponse
import java.util.Optional; //導入方法依賴的package包/類
@Override
public MockResponse createResponse(MockRequest request) {
String subscriptionArn = request.getBodyParameters().get("SubscriptionArn");
Optional<Subscription> subscription =
findSubscriptionWithArn(subscriptionArn, request.getTopics().values());
String content = "<Attributes></Attributes>";
if (subscription.isPresent()) {
content = getAttributeResponseXml(subscription.get().getAttributes());
}
return new MockResponse(request.utils().successBody(GET_SUB_ATTR_ACTION, content));
}
示例10: checkEnvironmentVariableConsistence
import java.util.Optional; //導入方法依賴的package包/類
private void checkEnvironmentVariableConsistence(EnvironmentVariable environmentVariable, String containerName) {
if (environmentVariable.getKeyEnv() == null || environmentVariable.getKeyEnv().isEmpty())
throw new CheckException("This key is not consistent !");
if (!environmentVariable.getKeyEnv().matches("^[-a-zA-Z0-9_]*$"))
throw new CheckException("This key is not consistent : " + environmentVariable.getKeyEnv());
List<EnvironmentVariable> environmentList = environmentDAO.findByContainer(containerName);
Optional<EnvironmentVariable> value = environmentList.stream()
.filter(v -> v.getKeyEnv().equals(environmentVariable.getKeyEnv())).findFirst();
if (value.isPresent())
throw new CheckException("This key already exists");
}
示例11: fenwayPark
import java.util.Optional; //導入方法依賴的package包/類
@Test
public void fenwayPark() {
Optional<Site> optionalSite = service.getLatLng("Fenway Park",
"4 David Ortiz Drive",
"Boston",
"MA");
if (optionalSite.isPresent()) {
Site site = optionalSite.get();
logger.info(site::toString);
assertEquals(42.347, site.getLatitude(), 0.01);
assertEquals(-71.097, site.getLongitude(), 0.01);
}
}
示例12: fetchIp
import java.util.Optional; //導入方法依賴的package包/類
@VisibleForTesting
InetAddress fetchIp() throws UnknownHostException {
final Optional<InetAddress> ip = this.tryToFetchFromProviders();
if (ip.isPresent()) {
logger.info("Successfully fetch public IP address: {}", ip.get().getHostAddress());
return ip.get();
}
if (this.ipAddress != null) {
logger.warn("Failed to fetch public IP address, reuse last known IP address: {}", this.ipAddress.getHostAddress());
return this.ipAddress;
}
logger.warn("Failed to fetch public IP address, fallback to localhost");
return InetAddress.getLocalHost();
}
示例13: getDeviceEnergy
import java.util.Optional; //導入方法依賴的package包/類
private SpeechletResponse getDeviceEnergy(final Intent intent, final Locale locale) {
Slot deviceSlot = intent.getSlot(DEVICE_SLOT);
if (deviceSlot == null || deviceSlot.getValue() == null) {
return newResponse("Gerät nicht erkannt");
}
try {
Optional<SwitchDevice> dev = findDevice(deviceSlot.getValue());
if (!dev.isPresent()) {
return newResponse(String.format("Das Gerät %s ist mir nicht bekannt", deviceSlot.getValue()));
}
SwitchDevice device = dev.get();
if (!device.isPresent()) {
return newResponse(String.format("%s %s ist aktuell nicht verfügbar", toGroupName(device), deviceSlot.getValue()));
}
if (!device.isPowermeter()) {
return newResponse(String.format("%s %s hat keine Energieverbauchswerte", toGroupName(device), deviceSlot.getValue()));
}
StringBuilder sb = new StringBuilder();
sb.append("Der aktuelle Energie Verbrauch von ").append(deviceSlot.getValue()).append(" ist ")
.append(FritzUtils.getPower(locale, device.getPower()));
if (device.getEnergy() > 0) {
sb.append(" mit einem Gesamtverbrauch von ").append(FritzUtils.getEnergy(locale, device.getEnergy()));
}
return newResponse("Fritz Home Energie", sb.toString());
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return newResponse("Es ist ein Fehler beim Lesen des Energie Verbrauches aufgetreten");
}
示例14: setMaxEnergy
import java.util.Optional; //導入方法依賴的package包/類
/**
* Sets the max energy a player can hold.
*
* @param player The player
* @param maxAmount The new max amount
*/
public static void setMaxEnergy(EntityPlayer player, int maxAmount) {
Optional<IEnergy> optional = getEnergy(player);
if (optional.isPresent() && maxAmount >= 0) {
optional.get().setMax(maxAmount);
}
}
示例15: getLinkedRule
import java.util.Optional; //導入方法依賴的package包/類
/**
* Get the test rule of the specified type that's attached to the rule chain.
*
* @param <T> test rule type
* @param testRuleType test rule type
* @return {@link ScreenshotCapture} test rule
*/
public <T extends TestRule> T getLinkedRule(Class<T> testRuleType) {
Optional<T> optional = RuleChainWalker.getAttachedRule(ruleChain, testRuleType);
if (optional.isPresent()) {
return optional.get();
}
throw new IllegalStateException(testRuleType.getSimpleName() + " test rule wasn't found on the rule chain");
}