java.util.Optional#ifPresent ( )源码实例Demo

下面列出了java.util.Optional#ifPresent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: flink   文件: ReporterSetup.java
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;
}
 
@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;
}
 
源代码3 项目: Image-Cipher   文件: WindowController.java
@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");
  });
}
 
源代码4 项目: presto   文件: TestWebUi.java
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());
    }
}
 
@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);
      });
}
 
源代码6 项目: n4js   文件: NoDocumentationXcoreEcoreBuilder.java
@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));
}
 
源代码7 项目: incubator-ratis   文件: RaftServerProxy.java
/** 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);
}
 
源代码8 项目: mobi   文件: OntologyRecordVersioningService.java
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);
        }
    });
}
 
源代码9 项目: mobi   文件: SimpleMappingManager.java
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);
}
 
/**
 * 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");
    });
}
 
源代码11 项目: Lottor   文件: InitServiceImpl.java
/**
 * 根据配置文件初始化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);
    });
}
 
源代码12 项目: canon-sdk-java   文件: CameraManager.java
/**
 * 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;
}
 
源代码13 项目: tutorials   文件: StoreService.java
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);
    });
}
 
源代码14 项目: salt-netapi-client   文件: Grains.java
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>>() { });
}
 
源代码15 项目: bundletool   文件: PackageSubject.java
/**
 * 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]));
}
 
源代码16 项目: ditto   文件: NormalizedMessageMapper.java
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();
}
 
源代码17 项目: tutorials   文件: StoreService.java
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);
    });
}
 
private void addCollectionToHeader(MimeMessage message, String headerName, Optional<Collection<Serializable>> values) {
    values.ifPresent(collection ->
        collection.forEach(
            value -> addValueToHeader(message, headerName, value)));
}
 
源代码19 项目: tcases   文件: ListBuilder.java
/**
 * 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;
  }
 
源代码20 项目: c2mon   文件: TagConfigDocumentConverter.java
/**
 * 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;
}