Java Code Examples for java.util.Optional#ifPresent()
The following examples show how to use
java.util.Optional#ifPresent() .
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: ReporterSetup.java From flink with Apache License 2.0 | 6 votes |
private static List<ReporterSetup> setupReporters(Map<String, MetricReporterFactory> reporterFactories, List<Tuple2<String, Configuration>> reporterConfigurations) { List<ReporterSetup> reporterSetups = new ArrayList<>(reporterConfigurations.size()); for (Tuple2<String, Configuration> reporterConfiguration: reporterConfigurations) { String reporterName = reporterConfiguration.f0; Configuration reporterConfig = reporterConfiguration.f1; try { Optional<MetricReporter> metricReporterOptional = loadReporter(reporterName, reporterConfig, reporterFactories); metricReporterOptional.ifPresent(reporter -> { MetricConfig metricConfig = new MetricConfig(); reporterConfig.addAllToProperties(metricConfig); reporterSetups.add(createReporterSetup(reporterName, metricConfig, reporter)); }); } catch (Throwable t) { LOG.error("Could not instantiate metrics reporter {}. Metrics might not be exposed/reported.", reporterName, t); } } return reporterSetups; }
Example 2
Source File: ReplayControlInterfaceImpl.java From ocraft-s2client with MIT License | 6 votes |
@Override public boolean waitForReplay(Maybe<Response> waitFor) { Optional<ResponseStartReplay> responseStartReplay = control() .waitForResponse(waitFor) .flatMap(response -> response.as(ResponseStartReplay.class)); boolean isSuccess = responseStartReplay.isPresent() && !responseStartReplay.get().getError().isPresent(); if (!isSuccess) { responseStartReplay.ifPresent(startReplayErrorHandler()); } else { if (control().isInGame()) { if (isSet(replayPath)) { control().getObservation(); replayObserver.control().onGameStart(); replayObserver.onGameStart(); log.info("Replaying: '{}'", replayPath); } else { log.info("WaitForReplay: new replay loaded, replay path unknown"); } } else { log.error("WaitForReplay: not in a game."); isSuccess = false; } } return isSuccess; }
Example 3
Source File: RaftServerProxy.java From incubator-ratis with Apache License 2.0 | 6 votes |
/** Check the storage dir and add groups*/ void initGroups(RaftGroup group) { final Optional<RaftGroup> raftGroup = Optional.ofNullable(group); final Optional<RaftGroupId> raftGroupId = raftGroup.map(RaftGroup::getGroupId); RaftServerConfigKeys.storageDir(properties).parallelStream() .forEach((dir) -> Optional.ofNullable(dir.listFiles()) .map(Arrays::stream).orElse(Stream.empty()) .filter(File::isDirectory) .forEach(sub -> { try { LOG.info("{}: found a subdirectory {}", getId(), sub); final RaftGroupId groupId = RaftGroupId.valueOf(UUID.fromString(sub.getName())); if (!raftGroupId.filter(groupId::equals).isPresent()) { addGroup(RaftGroup.valueOf(groupId)); } } catch (Throwable t) { LOG.warn(getId() + ": Failed to initialize the group directory " + sub.getAbsolutePath() + ". Ignoring it", t); } })); raftGroup.ifPresent(this::addGroup); }
Example 4
Source File: WindowController.java From Image-Cipher with Apache License 2.0 | 6 votes |
@FXML public void launchImageProcessingWindow() { Optional<Parent> root = Optional.empty(); try { root = Optional.of(FXMLLoader.load( Main.class.getResource("/views/ImageProcessingWindow.fxml") )); } catch (IOException e) { logger.error(e); } root.ifPresent(parent -> { Scene scene = new Scene(parent, 900, 500); Stage stage = new Stage(); stage.setMinWidth(900); stage.setMinHeight(450); stage.setTitle("Image Processing"); stage.setScene(scene); stage.show(); logger.info("Opening ImageProcessingWindow"); }); }
Example 5
Source File: NoDocumentationXcoreEcoreBuilder.java From n4js with Eclipse Public License 1.0 | 6 votes |
@Override protected void handleAnnotations(XModelElement xModelElement, EModelElement eModelElement) { super.handleAnnotations(xModelElement, eModelElement); // the following special handling only applies to EPackages if (!(eModelElement instanceof EPackage)) { return; } // obtain annotation that was created based on the automatic inference of copyright headers Optional<EAnnotation> inferredAnnotations = eModelElement.getEAnnotations().stream() .filter(a -> a.getSource().equals(GenModelPackage.eNS_URI)) // find annotation that is added automatically by inferring copyright header .filter(a -> a.getDetails().containsKey("documentation") && a.getDetails().size() == 1) .findFirst(); // removes annotation from container inferredAnnotations.ifPresent(a -> eModelElement.getEAnnotations().remove(a)); }
Example 6
Source File: DeclarationSearcherTest.java From meghanada-server with GNU General Public License v3.0 | 6 votes |
@Test public void testClassDeclaration01() throws Exception { File f = new File( project.getProjectRootPath(), "./src/main/java/meghanada/server/emacs/EmacsServer.java") .getCanonicalFile(); assertTrue(f.exists()); final DeclarationSearcher searcher = getSearcher(); final Optional<Declaration> result = debugIt( () -> { return searcher.searchDeclaration(f, 31, 20, "ServerSocket"); }); assertNotNull(result); assertTrue(result.isPresent()); result.ifPresent( declaration -> { assertEquals("ServerSocket", declaration.scopeInfo); assertEquals("java.net.ServerSocket", declaration.signature); }); }
Example 7
Source File: TestWebUi.java From presto with Apache License 2.0 | 6 votes |
private void testFailedLogin(URI httpsUrl, Optional<String> username, Optional<String> password) throws IOException { CookieManager cookieManager = new CookieManager(); OkHttpClient client = this.client.newBuilder() .cookieJar(new JavaNetCookieJar(cookieManager)) .build(); FormBody.Builder formData = new FormBody.Builder(); username.ifPresent(value -> formData.add("username", value)); password.ifPresent(value -> formData.add("password", value)); Request request = new Request.Builder() .url(getLoginLocation(httpsUrl)) .post(formData.build()) .build(); try (Response response = client.newCall(request).execute()) { assertEquals(response.code(), SC_SEE_OTHER); assertEquals(response.header(LOCATION), getLoginHtmlLocation(httpsUrl)); assertTrue(cookieManager.getCookieStore().getCookies().isEmpty()); } }
Example 8
Source File: OntologyRecordVersioningService.java From mobi with GNU Affero General Public License v3.0 | 5 votes |
private void updateOntologyIRI(com.mobi.rdf.api.Resource recordId, Stream<Statement> additions, RepositoryConnection conn) { OntologyRecord record = catalogUtils.getObject(recordId, ontologyRecordFactory, conn); Optional<com.mobi.rdf.api.Resource> iri = record.getOntologyIRI(); iri.ifPresent(resource -> ontologyCache.clearCacheImports(resource)); getNewOntologyIRI(additions).ifPresent(newIRI -> { if (!iri.isPresent() || !newIRI.equals(iri.get())) { testOntologyIRIUniqueness(newIRI); record.setOntologyIRI(newIRI); catalogUtils.updateObject(record, conn); ontologyCache.clearCacheImports(newIRI); } }); }
Example 9
Source File: StoreService.java From tutorials with MIT License | 5 votes |
public void createRandomProduct(Integer storeId) { Optional<Store> storeOpt = this.storeRepository.findById(storeId); storeOpt.ifPresent(store -> { Random random = new Random(); Product product = new Product("Product#" + random.nextInt(), random.nextDouble() * 100); store.addProduct(product); storeRepository.save(store); }); }
Example 10
Source File: NormalizedMessageMapper.java From ditto with Eclipse Public License 2.0 | 5 votes |
private ExternalMessage flattenAsThingChange(final Adaptable adaptable) { final TopicPath topicPath = adaptable.getTopicPath(); final Payload payload = adaptable.getPayload(); final JsonPointer path = JsonPointer.of(payload.getPath()); final Optional<JsonValue> payloadValue = payload.getValue(); final Optional<JsonObject> extraData = payload.getExtra(); final JsonObjectBuilder builder = JsonObject.newBuilder(); builder.set(THING_ID, ThingId.of(topicPath.getNamespace(), topicPath.getId()).toString()); // enrich with data selected by "extraFields", do this first - the actual changed data applied on top of that: extraData.ifPresent(builder::setAll); if (path.isEmpty() && payloadValue.isPresent()) { final JsonValue value = payloadValue.get(); if (value.isObject()) { value.asObject().forEach(builder::set); } else { // this is impossible; the adaptable should be the protocol message of an event. throw new IllegalStateException("Got adaptable with empty path and non-object value: " + adaptable); } } else { payloadValue.ifPresent(jsonValue -> builder.set(path, jsonValue)); } payload.getTimestamp().ifPresent(timestamp -> builder.set(MODIFIED, timestamp.toString())); payload.getRevision().ifPresent(revision -> builder.set(REVISION, revision)); builder.set(ABRIDGED_ORIGINAL_MESSAGE, abridgeMessage(adaptable)); final JsonObject result = jsonFieldSelector == null ? builder.build() : builder.build().get(jsonFieldSelector); return ExternalMessageFactory.newExternalMessageBuilder(Collections.emptyMap()) .withTopicPath(adaptable.getTopicPath()) .withText(result.toString()) .build(); }
Example 11
Source File: PackageSubject.java From bundletool with Apache License 2.0 | 5 votes |
/** * Checks if the package does not have a specific entry. * * <p>Resource must be specified in "type/entry" format. */ public void hasNoResource(String resourceName) { checkArgument( RESOURCE_PATTERN.matcher(resourceName).matches(), String.format( "Resource needs to follow pattern: %s but looks like %s", RESOURCE_PATTERN.pattern(), resourceName)); String[] parts = resourceName.split("/"); checkState( parts.length == 2, "Resource has incorrect format, expecting type/entry, but got: " + resourceName); Optional<Type> foundType = findType(parts[0]); foundType.ifPresent(type -> new TypeSubject(metadata, type).notContainingResource(parts[1])); }
Example 12
Source File: Grains.java From salt-netapi-client with MIT License | 5 votes |
public static LocalCall<Map<String, Object>> set(String key, Optional<Map<String, Object>> extraArgs) { LinkedHashMap<String, Object> args = new LinkedHashMap<>(); args.put("key", key); extraArgs.ifPresent(args::putAll); return new LocalCall<>("grains.set", Optional.empty(), Optional.of(args), new TypeToken<Map<String, Object>>() { }); }
Example 13
Source File: StoreService.java From tutorials with MIT License | 5 votes |
public void rebrandStore(int storeId, String updatedName) { Optional<Store> storeOpt = storeRepository.findById(storeId); storeOpt.ifPresent(store -> { store.setName(updatedName); store.getProducts().forEach(product -> { product.setNamePrefix(updatedName); }); storeRepository.save(store); }); }
Example 14
Source File: CameraManager.java From canon-sdk-java with MIT License | 5 votes |
/** * Cannot be called from dispatcher thread * * @param camera camera to reconnect * @return true if camera is connected, false otherwise * @throws InterruptedException if interrupted while waiting to check status or reconnect */ private static boolean reconnect(final CanonCamera camera) throws InterruptedException { final String serialNumber = camera.getSerialNumber() .orElseThrow(() -> new IllegalStateException("Cameras managed always have the serial number set")); final OpenSessionOption openSessionOption = new OpenSessionOptionBuilder() .setCameraBySerialNumber(serialNumber) .setRegisterObjectEvent(true) .setRegisterPropertyEvent(true) .setRegisterStateEvent(true) .build(); final OpenSessionCommand openSessionCommand = new OpenSessionCommand(openSessionOption); openSessionCommand.setTimeout(CONNECT_FAST_TIMEOUT); CanonFactory.commandDispatcher().scheduleCommand(openSessionCommand); try { final EdsdkLibrary.EdsCameraRef cameraRef = openSessionCommand.get(); final Optional<EdsdkLibrary.EdsCameraRef> cameraCameraRef = camera.getCameraRef(); // we replace if ref has changed camera.setCameraRef(cameraRef); cameraCameraRef.ifPresent(ref -> { if (ref != cameraRef) { log.warn("On reconnect, cameraRef was different than previous one for camera: {}", serialNumber); } // The open session command has returned a ref with an incremented count of 1 so we always need to decrement once as well (not an open only command) ReleaseUtil.release(ref); }); return true; } catch (ExecutionException ignored) { log.warn("Failed to reopen session for camera {}", serialNumber); } return false; }
Example 15
Source File: InitServiceImpl.java From Lottor with MIT License | 5 votes |
/** * 根据配置文件初始化spi * * @param txConfig 配置信息 */ private void loadSpi(TxConfig txConfig) { //spi serialize final SerializeProtocolEnum serializeProtocolEnum = SerializeProtocolEnum.acquireSerializeProtocol(txConfig.getSerializer()); final ServiceLoader<ObjectSerializer> objectSerializers = ServiceBootstrap.loadAll(ObjectSerializer.class); final Optional<ObjectSerializer> serializer = StreamSupport.stream(objectSerializers.spliterator(), false) .filter(objectSerializer -> Objects.equals(objectSerializer.getScheme(), serializeProtocolEnum.getSerializeProtocol())).findFirst(); //spi RecoverRepository support final CompensationCacheTypeEnum compensationCacheTypeEnum = CompensationCacheTypeEnum.acquireCompensationCacheType(txConfig.getCacheType()); final ServiceLoader<TransactionOperateRepository> recoverRepositories = ServiceBootstrap.loadAll(TransactionOperateRepository.class); final Optional<TransactionOperateRepository> repositoryOptional = StreamSupport.stream(recoverRepositories.spliterator(), false) .filter(recoverRepository -> Objects.equals(recoverRepository.getScheme(), compensationCacheTypeEnum.getCompensationCacheType())) .findFirst(); //将compensationCache实现注入到spring容器 repositoryOptional.ifPresent(repository -> { serializer.ifPresent(repository::setSerializer); SpringBeanUtils.getInstance().registerBean(TransactionOperateRepository.class.getName(), repository); }); }
Example 16
Source File: MovementClassDuplicatesValidator.java From web-budget with GNU General Public License v3.0 | 5 votes |
/** * If the {@link MovementClass} is not saved, don't compare the found with the one to be validated * * @param value the value to be evaluated */ private void validateNotSaved(MovementClass value) { final Optional<MovementClass> found = this.find(value.getName(), value.getCostCenter().getName()); found.ifPresent(movementClass -> { throw new BusinessLogicException("error.movement-class.duplicated"); }); }
Example 17
Source File: SimpleMappingManager.java From mobi with GNU Affero General Public License v3.0 | 5 votes |
private MappingWrapper getWrapperFromModel(Model model) { Collection<Mapping> mappings = mappingFactory.getAllExisting(model); if (mappings.size() != 1) { throw new MobiException("Input source must contain exactly one Mapping resource."); } Mapping mapping = mappings.iterator().next(); Optional<IRI> versionIriOpt = mapping.getVersionIRI(); SimpleMappingId.Builder builder = new SimpleMappingId.Builder(vf) .mappingIRI(vf.createIRI(mapping.getResource().stringValue())); versionIriOpt.ifPresent(builder::versionIRI); Collection<ClassMapping> classMappings = classMappingFactory.getAllExisting(model); return new SimpleMappingWrapper(builder.build(), mapping, classMappings, model); }
Example 18
Source File: MailAttributesListToMimeHeaders.java From james-project with Apache License 2.0 | 4 votes |
private void addCollectionToHeader(MimeMessage message, String headerName, Optional<Collection<Serializable>> values) { values.ifPresent(collection -> collection.forEach( value -> addValueToHeader(message, headerName, value))); }
Example 19
Source File: ListBuilder.java From tcases with MIT License | 4 votes |
/** * If present, appends a new element to the list for this builder. */ public ListBuilder<T> add( Optional<T> element) { element.ifPresent( e -> list_.add( e)); return this; }
Example 20
Source File: TagConfigDocumentConverter.java From c2mon with GNU Lesser General Public License v3.0 | 2 votes |
/** * Convert a {@link Tag} and list of {@link Alarm}s to a {@link TagConfigDocument}. * * @param tag the tag * @param alarms the alarms * @return the tag config document */ public Optional<TagConfigDocument> convert(final Tag tag, final List<Alarm> alarms) { Optional<TagConfigDocument> document = this.convert(tag); document.ifPresent(doc -> doc.put("alarms", alarms.stream().map((new BaseAlarmDocumentConverter())::convert).collect(toList()))); return document; }