當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。