当前位置: 首页>>代码示例>>Java>>正文


Java Optional.get方法代码示例

本文整理汇总了Java中java.util.Optional.get方法的典型用法代码示例。如果您正苦于以下问题:Java Optional.get方法的具体用法?Java Optional.get怎么用?Java Optional.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.Optional的用法示例。


在下文中一共展示了Optional.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: parseValue

import java.util.Optional; //导入方法依赖的package包/类
@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
    String arg = args.next().toLowerCase();

    // Try
    GameRegistry registry = Sponge.getRegistry();
    Optional<? extends CatalogType> catalogType = registry.getType(this.type, arg);
    if (!catalogType.isPresent() && !arg.contains(":")) {
        catalogType = registry.getType(this.type, "minecraft:" + arg);
        if (!catalogType.isPresent()) {
            catalogType = registry.getType(this.type, "happytrails:" + arg);
        }
    }

    final String trimmedId = catalogType
        .map(trail -> trail.getId().contains(":") ? trail.getId().split(":")[1] : trail.getId())
        .orElse("");
    if (catalogType.isPresent() && source.hasPermission(this.permissionPrefix + trimmedId)) {
        return catalogType.get();
    }

    throw args.createError(Text.of(TextColors.RED, ""));
}
 
开发者ID:gabizou,项目名称:HappyTrails,代码行数:25,代码来源:TrailCommands.java

示例2: onMessageChannelChat

import java.util.Optional; //导入方法依赖的package包/类
@Listener(order = Order.LATE)
public void onMessageChannelChat(MessageChannelEvent.Chat event) {
    if (event.isCancelled()) {
        return;
    }

    Optional<Player> playerOpt = event.getCause().first(Player.class);
    if (!playerOpt.isPresent()) {
        return;
    }
    Player player = playerOpt.get();

    ClanPlayerImpl clanPlayer = ClansImpl.getInstance().getClanPlayer(player.getUniqueId());
    if (clanPlayer != null && clanPlayer.getClan() != null) {
        PlayerChatState chatState = clanPlayer.getChatState();
        PlayerChatState tempChatState = clanPlayer.getTempChatState();

        if (tempChatState == null) {
            handleChat(player, clanPlayer, chatState, event);
        } else {
            handleChat(player, clanPlayer, tempChatState, event);
            clanPlayer.setTempChatState(null);
        }
    }
}
 
开发者ID:iLefty,项目名称:mcClans,代码行数:26,代码来源:PlayerChatListener.java

示例3: downloadUpdate

import java.util.Optional; //导入方法依赖的package包/类
/**
 * Downloads the latest version and restarts the client.
 */
private void downloadUpdate() {
	try {
		final Optional<GHRelease> releaseOptional = UpdateUtility.getRelease();

		if (releaseOptional.isPresent()) {
			final GHRelease release = releaseOptional.get();
			final String updateUrl = release.getAssets().get(0).getBrowserDownloadUrl();
			final URI url = new URI(updateUrl);
			FileUtility.downloadFile(url.toURL(), PathConstants.SAMPEX_TEMP_JAR, mainController
					.progressProperty(), (int) release.getAssets().get(0).getSize());
		}
	}
	catch (final IOException | URISyntaxException exception) {
		Logging.error("Couldn't retrieve update.", exception);
	}
}
 
开发者ID:Bios-Marcel,项目名称:ServerBrowser,代码行数:20,代码来源:Client.java

示例4: rate

import java.util.Optional; //导入方法依赖的package包/类
@Transactional
public boolean rate(int rating, long taskInstanceId) {
  Optional<TaskInstance> taskInstanceOpt = taskInstanceService.findById(taskInstanceId);

  if (!taskInstanceOpt.isPresent()) {
    return false;
  }

  TaskInstance taskInstance = taskInstanceOpt.get();

  if (taskInstance.isRated()
      || taskInstance.getUser().getId() != userService.getCurrentUser().getId()) {
    // Task has already been rated or the instance doesn't belong to the current user, ignore.
    return false;
  }

  Task task = taskInstance.getTask();

  taskInstance.setRating(rating);
  task.addRating(rating);

  return true;
}
 
开发者ID:tdd-pingis,项目名称:tdd-pingpong,代码行数:24,代码来源:GameplayService.java

示例5: addNode

import java.util.Optional; //导入方法依赖的package包/类
/**
 * Convenience method for adding a single node's connection to ClusterConnectionReport
 *
 * @param node Node to add
 * @param addressList client side of the connections this node has
 * @param serverAddress the address where this node is listening
 * @return report for added node.
 */
public NodeConnectionReport addNode(
    AbstractNode node, List<SocketAddress> addressList, SocketAddress serverAddress) {
  Long dcId = node.getDataCenter().getId();
  Optional<DataCenterConnectionReport> optionalDatacenterReport =
      dataCenters.stream().filter(dc -> dc.getId().equals(dcId)).findFirst();
  DataCenterConnectionReport datacenterReport;
  if (optionalDatacenterReport.isPresent()) {
    datacenterReport = optionalDatacenterReport.get();
  } else {
    datacenterReport = new DataCenterConnectionReport(dcId, this);
    this.addDataCenter(datacenterReport);
  }
  NodeConnectionReport nodeReport =
      new NodeConnectionReport(node.getId(), addressList, serverAddress, datacenterReport);
  datacenterReport.addNode(nodeReport);
  return nodeReport;
}
 
开发者ID:datastax,项目名称:simulacron,代码行数:26,代码来源:ClusterConnectionReport.java

示例6: imageStream

import java.util.Optional; //导入方法依赖的package包/类
public ImageStreamBuilder imageStream(String name) {
	ImageStreamBuilder builder;
	Optional<ImageStreamBuilder> orig = images.stream().filter(b -> b.getName().equals(name)).findFirst();
	if (orig.isPresent()) {
		LOGGER.debug("Trying to create image stream that already exists.");
		builder = orig.get();
	} else {
		builder = new ImageStreamBuilder(this, name);
		images.add(builder);
	}

	return builder;
}
 
开发者ID:xtf-cz,项目名称:xtf,代码行数:14,代码来源:ApplicationBuilder.java

示例7: findDeviceBySerial

import java.util.Optional; //导入方法依赖的package包/类
public Device findDeviceBySerial(String serial) {
    if (this.serial.equals(serial)) {
        return this;
    }

    for (Room room : rooms) {
        Optional<Device> device = room.devices.stream().filter(d -> d.getSerial().equals(serial)).findFirst();
        if (device.isPresent()) {
            return device.get();
        }
    }

    throw new IllegalArgumentException(String.format(Locale.ROOT, "Device with serial [%s] does not exist", serial));
}
 
开发者ID:spinscale,项目名称:maxcube-java,代码行数:15,代码来源:Cube.java

示例8: injectContext

import java.util.Optional; //导入方法依赖的package包/类
public static void injectContext(View codeBehind, ContextImpl context) {

        Optional<Field> contextField = getContextField(codeBehind.getClass());

        if (contextField.isPresent()) {
            Field field = contextField.get();
            ReflectionUtils.accessField(field, () -> {
                field.set(codeBehind, context);
            }, "Can't inject Context into the view <" + codeBehind + ">");
        }
    }
 
开发者ID:cmlanche,项目名称:javafx-qiniu-tinypng-client,代码行数:12,代码来源:ViewLoaderReflectionUtils.java

示例9: getObject

import java.util.Optional; //导入方法依赖的package包/类
@Nonnull
public T getObject(String key, Supplier<T> constructor) {
    Optional<T> o = data.get(key);
    if(o == null || !o.isPresent()) {
        T t = constructor.get();
        data.put(key, Optional.of(t));
        return t;
    }
    return o.get();
}
 
开发者ID:natanbc,项目名称:GabrielBot,代码行数:11,代码来源:JedisSerializatorDataManager.java

示例10: actionButtonFilter

import java.util.Optional; //导入方法依赖的package包/类
@FXML
private void actionButtonFilter(ActionEvent event) {
    LOGGER.info("Filter button clicked.");
    if (buttonFilter.isSelected()) {
        TextInputDialog textInputDialog = new TextInputDialog(filter);
        textInputDialog.setHeaderText("Set filter");
        textInputDialog.setResizable(true);
        Optional<String> filterOptional = textInputDialog.showAndWait();
        if (filterOptional.isPresent()) {
            this.filter = filterOptional.get();
        } else {
            this.filter = "";
        }
    }
}
 
开发者ID:hylkevds,项目名称:SensorThingsManager,代码行数:16,代码来源:ControllerCollection.java

示例11: shouldMapAllPrimitivesToWrapperTypes

import java.util.Optional; //导入方法依赖的package包/类
@Test
public void shouldMapAllPrimitivesToWrapperTypes() {
  int id = 1;
  short sid = 2;
  long lid = 3L;
  float fid = 4f;
  double did = 5.0;
  char cid = 'a';
  boolean bid = true;
  byte byid = 6;

  PrimitiveTypeTo primitiveTypeTo = new PrimitiveTypeTo();
  primitiveTypeTo.setBid(bid);
  primitiveTypeTo.setByid(byid);
  primitiveTypeTo.setCid(cid);
  primitiveTypeTo.setDid(did);
  primitiveTypeTo.setFid(fid);
  primitiveTypeTo.setId(id);
  primitiveTypeTo.setLid(lid);
  primitiveTypeTo.setSid(sid);

  Optional<WrapperTypeTo> wrapperTypeToOptional =
      MeMapper.getMapperFrom(primitiveTypeTo).mapTo(WrapperTypeTo.class);

  assertTrue(wrapperTypeToOptional.isPresent());
  WrapperTypeTo wrapperTypeTo = wrapperTypeToOptional.get();
  assertEquals((Integer) id, wrapperTypeTo.getId());
  assertEquals((Short) sid, wrapperTypeTo.getSid());
  assertEquals((Long) lid, wrapperTypeTo.getLid());
  assertEquals((Float) fid, wrapperTypeTo.getFid());
  assertEquals((Double) did, wrapperTypeTo.getDid());
  assertEquals((Character) cid, wrapperTypeTo.getCid());
  assertEquals((Boolean) bid, wrapperTypeTo.getBid());
  assertEquals((Byte) byid, wrapperTypeTo.getByid());
}
 
开发者ID:mental-party,项目名称:meparty,代码行数:36,代码来源:MeMapperTest.java

示例12: readVisualSearchResult

import java.util.Optional; //导入方法依赖的package包/类
public String readVisualSearchResult(final String payload,
		Optional<Map<String, String>> parameters) {
	Boolean collectResults = parameters.isPresent();
	Map<String, String> collector = (collectResults) ? parameters.get()
			: new HashMap<>();
	String result = readData(payload, Optional.of(collector));
	assertTrue(collector.containsKey("ElementId"));
	// NOTE: elementCodeName will not be set if
	// user clicked the SWD Table Close Button
	// ElementId is always set
	// TODO: read the 'ElementSelectedBy'
	return result;
}
 
开发者ID:sergueik,项目名称:SWET,代码行数:14,代码来源:Utils.java

示例13: routeFromMultipleStartPoints

import java.util.Optional; //导入方法依赖的package包/类
@Test
public void routeFromMultipleStartPoints() {
	Stop chemnitz = network.chemnitz();
	RelativeTime timeToChemnitz = RelativeTime.of(30, MINUTES);
	StopPath viaChemnitz = new StopPath(chemnitz, timeToChemnitz);
	
	Stop dortmund = network.dortmund();
	RelativeTime timeToDortmund = RelativeTime.of(1, HOURS);
	StopPath viaDortmund = new StopPath(dortmund, timeToDortmund);

	Stop berlin = network.berlin();
	RelativeTime walkTimeInBerlin = RelativeTime.of(5, MINUTES);
	StopPath toPlaceInBerlin = new StopPath(berlin, walkTimeInBerlin);

	Time atOneOClock = oneOClock;
	Connection chemnitzToBerlin = network.chemnitzToBerlin();
	Time includingEgresspath = fourOClock.add(walkTimeInBerlin);
	
	StopPaths starts = DefaultStopPaths.from(asList(viaChemnitz, viaDortmund));
	StopPaths ends = DefaultStopPaths.from(asList(toPlaceInBerlin));
	
	RouteSearch connectionScan = network.connectionScan();
	
	Optional<PublicTransportRoute> potentialRoute = connectionScan.findRoute(starts, ends, atOneOClock);
	
	assertThat(potentialRoute, isPresent());
	PublicTransportRoute route = potentialRoute.get();
	assertThat(route.arrival(), is(equalTo(includingEgresspath)));
	assertThat(route.start(), is(equalTo(chemnitz)));
	assertThat(route.end(), is(equalTo(berlin)));
	assertThat(route.connections(), contains(chemnitzToBerlin));
}
 
开发者ID:mobitopp,项目名称:connection-scan,代码行数:33,代码来源:SimpleTransitExampleTest.java

示例14: signIdToken

import java.util.Optional; //导入方法依赖的package包/类
private String signIdToken(final OidcRegisteredService svc, final JsonWebSignature jws) throws Exception {
    final Optional<RsaJsonWebKey> jwks = defaultJsonWebKeystoreCache.get(this.issuer);
    if (!jwks.isPresent()) {
        throw new IllegalArgumentException("Service " + svc.getServiceId()
                + " with client id " + svc.getClientId()
                + " is configured to sign id tokens, yet no JSON web key is available");
    }
    final RsaJsonWebKey jsonWebKey = jwks.get();
    LOGGER.debug("Found JSON web key to sign the id token: [{}]", jsonWebKey);
    if (jsonWebKey.getPrivateKey() == null) {
        throw new IllegalArgumentException("JSON web key used to sign the id token has no associated private key");
    }
    prepareJsonWebSignatureForIdTokenSigning(svc, jws, jsonWebKey);
    return jws.getCompactSerialization();
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:16,代码来源:OidcIdTokenSigningAndEncryptionService.java

示例15: getPlayer

import java.util.Optional; //导入方法依赖的package包/类
Player getPlayer() {
    Player temp = this.playerReference.get();
    if (temp != null) {
        return temp;
    }
    final Optional<Player> player = Sponge.getServer().getPlayer(this.playerId);
    if (!player.isPresent()) {
        throw new IllegalStateException("Outdated player wrapper reference!");
    }
    this.playerReference = new WeakReference<>(player.get());
    return player.get();
}
 
开发者ID:gabizou,项目名称:HappyTrails,代码行数:13,代码来源:PlayerWrapper.java


注:本文中的java.util.Optional.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。