Java Code Examples for java.util.Optional.get()

The following are Jave code examples for showing how to use get() of the java.util.Optional class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: HappyTrails   File: TrailCommands.java   View Source Code Vote up 6 votes
@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, ""));
}
 
Example 2
Project: mcClans   File: PlayerChatListener.java   View Source Code Vote up 6 votes
@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);
        }
    }
}
 
Example 3
Project: ServerBrowser   File: Client.java   View Source Code Vote up 6 votes
/**
 * 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);
	}
}
 
Example 4
Project: tdd-pingpong   File: GameplayService.java   View Source Code Vote up 6 votes
@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;
}
 
Example 5
Project: simulacron   File: ClusterConnectionReport.java   View Source Code Vote up 6 votes
/**
 * 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;
}
 
Example 6
Project: xtf   File: ApplicationBuilder.java   View Source Code Vote up 5 votes
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;
}
 
Example 7
Project: maxcube-java   File: Cube.java   View Source Code Vote up 5 votes
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));
}
 
Example 8
Project: javafx-qiniu-tinypng-client   File: ViewLoaderReflectionUtils.java   View Source Code Vote up 5 votes
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 + ">");
        }
    }
 
Example 9
Project: GabrielBot   File: JedisSerializatorDataManager.java   View Source Code Vote up 5 votes
@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();
}
 
Example 10
Project: SensorThingsManager   File: ControllerCollection.java   View Source Code Vote up 5 votes
@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 = "";
        }
    }
}
 
Example 11
Project: meparty   File: MeMapperTest.java   View Source Code Vote up 5 votes
@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());
}
 
Example 12
Project: SWET   File: Utils.java   View Source Code Vote up 5 votes
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;
}
 
Example 13
Project: connection-scan   File: SimpleTransitExampleTest.java   View Source Code Vote up 5 votes
@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));
}
 
Example 14
Project: cas-5.1.0   File: OidcIdTokenSigningAndEncryptionService.java   View Source Code Vote up 5 votes
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();
}
 
Example 15
Project: HappyTrails   File: PlayerWrapper.java   View Source Code Vote up 5 votes
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();
}
 
Example 16
Project: xtf   File: ApplicationBuilder.java   View Source Code Vote up 5 votes
/**
 * Gets a ConfigMap route with given name. If no such ConfigMap exists, it is created
 *
 * @param configMapName
 * 		name of the ConfigMap
 * @return ConfigMap with given name.
 */
public ConfigMapWithPropertyFilesBuilder configMap(final String configMapName) {
	ConfigMapWithPropertyFilesBuilder result;
	Optional<ConfigMapWithPropertyFilesBuilder> orig = configMaps.stream().filter(r -> r.getName().equals(configMapName)).findFirst();
	if (orig.isPresent()) {
		LOGGER.debug("Trying to create configMap that already exists.");
		result = orig.get();
	} else {
		result = new ConfigMapWithPropertyFilesBuilder(configMapName);
		configMaps.add(result);
	}
	return result;
}
 
Example 17
Project: Solar   File: BlockQimranut.java   View Source Code Vote up 5 votes
@Override
public ItemStack getItem(World world, BlockPos pos, IBlockState state) {
	Optional<TileQimranut> optional = getTile(TileQimranut.class, world, pos);
	if(optional.isPresent()) {
		TileQimranut qimranut = optional.get();
		ItemStack stack = new ItemStack(Item.getItemFromBlock(this));
		qimranut.getKey().ifPresent(uuid -> {
			((IEntangledStack) stack.getItem()).setKey(stack, uuid);
		});
		return stack;
	}
	return super.getItem(world, pos, state);
}
 
Example 18
Project: mux2fs   File: MuxFs.java   View Source Code Vote up 5 votes
private int open(String path, FileHandleFiller filler, Path muxFile, List<Path> subFiles, FileInfo info) {
	closedMuxFiles.invalidate(info);
	Muxer muxer = muxerFactory.from(muxFile, subFiles.get(0), tempDir);
	Muxer previous = muxFiles.putIfAbsent(info, muxer); // Others might be racing the same file
	if (previous != null) { // They won the race
		muxer = previous;
	}
	try {
		muxer.start();
		muxer.waitForOutput();
	} catch (IOException e) {
		// Something dun goofed. Second best thing is to open the original file then.
		logger.warn("Muxing failed, falling back to unmuxed file {}", muxFile, e);
		// Invalidate the broken muxer. This means the next open will try again, which might not be a good strategy.
		muxFiles.remove(info, muxer);
		return super.open(path, filler);
	}
	Optional<Path> optionalOutput = muxer.getOutput();
	if (!optionalOutput.isPresent()) {
		logger.warn("Muxing failed! muxer.getOutput().isPresent() == false, falling back to unmuxed file {}", muxFile);
		// Invalidate the broken muxer. This means the next open will try again, which might not be a good strategy.
		muxFiles.remove(info, muxer);
		return super.open(path, filler); // Fall back to original if no result
	}
	Path output = optionalOutput.get();
	Recorder recorder = FileHandleFiller.Recorder.wrap(filler);
	int result = super.openReal(output, recorder);
	if (result == SUCCESS) {
		updateMuxCaches(info, muxer, output, recorder);
	} else {
		logger.warn("Failed to open muxed file {}, falling back to unmuxed file {}", output, muxFile);
		muxFiles.remove(info, muxer);
		safeDelete(output);
		result = super.openReal(muxFile, filler);
	}
	return result;
}
 
Example 19
Project: NoraUi   File: Result.java   View Source Code Vote up 4 votes
public O failure() {
    final Optional<O> o = Optional.ofNullable(error);
    return o.isPresent() ? o.get() : null;
}
 
Example 20
Project: tokenapp-backend   File: RegisterController.java   View Source Code Vote up 4 votes
@RequestMapping(value = "/register", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE,
        produces = APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<?> register(@Valid @RequestBody RegisterRequest registerRequest,
                                  @Context HttpServletRequest httpServletRequest)
        throws BaseException {
    // Get IP address from request
    String ipAddress = httpServletRequest.getHeader("X-Real-IP");
    if (ipAddress == null)
        ipAddress = httpServletRequest.getRemoteAddr();
    LOG.info("/register called from {} with email: {}", ipAddress, registerRequest.getEmail());

    try {
        String emailConfirmationToken = null;
        Optional<Investor> oInvestor = investorRepository.findOptionalByEmail(registerRequest.getEmail());
        if (oInvestor.isPresent()) {
            emailConfirmationToken = oInvestor.get().getEmailConfirmationToken();
        } else {
            emailConfirmationToken = generateRandomUUID();
            oInvestor = Optional.of(createInvestor(registerRequest.getEmail(), emailConfirmationToken, ipAddress));
            Investor investor = oInvestor.get();
            investorRepository.save(investor);
            LOG.debug("Investor saved to the database: email="
                    + investor.getEmail() + "), emailConfirmationToken="
                    + investor.getEmailConfirmationToken());
        }
        // If the investor has a wallet, and all the payIn addresses set,
        // then, send the summary email.
        // Else, send the confirmation email with the confirmationEmailToken
        if (oInvestor.isPresent()
                && oInvestor.get().getWalletAddress() != null
                && oInvestor.get().getPayInBitcoinPublicKey() != null
                && oInvestor.get().getPayInEtherPublicKey() != null){
            fileQueueService.addSummaryEmail(oInvestor.get());
            return ResponseEntity.ok().build();
        } else {
            URI emailLinkUri = new URI(frontendUrl + frontendWalletUrlPath + emailConfirmationToken);
            fileQueueService.addConfirmationEmail(oInvestor.get(), emailLinkUri);
            return ResponseEntity.created(new URI(frontendUrl)).build();
        }

    } catch (Exception e) {
        LOG.error("Unexpected exception in RegisterController: {} {}", e.getMessage(), e.getCause());
        throw new UnexpectedException();
    }
}