类java.util.Optional源码实例Demo

下面列出了怎么用java.util.Optional的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: teku   文件: GetChainHead.java
@OpenApi(
    path = ROUTE,
    method = HttpMethod.GET,
    summary = "Get information about the chain head.",
    tags = {TAG_BEACON},
    description =
        "Returns information about the head of the beacon chain including the finalized and "
            + "justified information.",
    responses = {
      @OpenApiResponse(status = RES_OK, content = @OpenApiContent(from = BeaconChainHead.class)),
      @OpenApiResponse(status = RES_NO_CONTENT, description = NO_CONTENT_PRE_GENESIS),
      @OpenApiResponse(status = RES_INTERNAL_ERROR)
    })
@Override
public void handle(final Context ctx) throws JsonProcessingException {
  ctx.header(Header.CACHE_CONTROL, CACHE_NONE);
  final Optional<BeaconChainHead> beaconChainHead = provider.getHeadState();
  if (beaconChainHead.isPresent()) {
    ctx.result(jsonProvider.objectToJSON(beaconChainHead.get()));
  } else {
    ctx.status(SC_NO_CONTENT);
  }
}
 
@Test
void shouldReturnDeletedResourceGroupWhenTerminateDatabaseServerAndMultipleResourceGroups() {
    PersistenceNotifier persistenceNotifier = mock(PersistenceNotifier.class);
    DatabaseStack databaseStack = mock(DatabaseStack.class);
    when(azureResourceGroupMetadataProvider.useSingleResourceGroup(any(DatabaseStack.class))).thenReturn(false);
    when(azureResourceGroupMetadataProvider.getResourceGroupName(cloudContext, databaseStack)).thenReturn(RESOURCE_GROUP_NAME);
    when(azureUtils.deleteResourceGroup(any(), anyString(), anyBoolean())).thenReturn(Optional.empty());
    List<CloudResource> cloudResources = List.of(
            CloudResource.builder()
                    .type(AZURE_DATABASE)
                    .reference("dbReference")
                    .name("dbName")
                    .status(CommonStatus.CREATED)
                    .params(Map.of())
                    .build());

    List<CloudResourceStatus> resourceStatuses = victim.terminateDatabaseServer(ac, databaseStack, cloudResources, false, persistenceNotifier);

    assertEquals(1, resourceStatuses.size());
    assertEquals(AZURE_RESOURCE_GROUP, resourceStatuses.get(0).getCloudResource().getType());
    assertEquals(DELETED, resourceStatuses.get(0).getStatus());
    verify(azureUtils).deleteResourceGroup(any(), eq(RESOURCE_GROUP_NAME), eq(false));
    verify(azureUtils, never()).deleteDatabaseServer(any(), anyString(), anyBoolean());
    verify(persistenceNotifier).notifyDeletion(any(), any());
}
 
源代码3 项目: flink   文件: ReporterSetup.java
private static Optional<MetricReporter> loadViaFactory(
		final String factoryClassName,
		final String reporterName,
		final Configuration reporterConfig,
		final Map<String, MetricReporterFactory> reporterFactories) {

	MetricReporterFactory factory = reporterFactories.get(factoryClassName);

	if (factory == null) {
		LOG.warn("The reporter factory ({}) could not be found for reporter {}. Available factories: ", factoryClassName, reporterName, reporterFactories.keySet());
		return Optional.empty();
	} else {
		final MetricConfig metricConfig = new MetricConfig();
		reporterConfig.addAllToProperties(metricConfig);

		return Optional.of(factory.createMetricReporter(metricConfig));
	}
}
 
@Override
public CapacityAllocations compute(CapacityRequirements capacityRequirements) {
    Map<AgentInstanceGroup, Integer> instanceAllocations = new HashMap<>();
    Map<Tier, ResourceDimension> resourceShortage = new HashMap<>();
    for (Tier tier : capacityRequirements.getTiers()) {
        // In Flex tier we have always 'DEFAULT' app, and if it is the only one, we should not scale the cluster
        // For other tiers we stop scaling, if there are no application SLAs configured
        boolean hasEnoughApps = (tier == Tier.Flex && capacityRequirements.getTierRequirements(tier).size() > 1)
                || (tier != Tier.Flex && capacityRequirements.getTierRequirements(tier).size() > 0);
        if (hasEnoughApps) {
            Optional<ResourceDimension> left = allocate(tier, capacityRequirements, instanceAllocations);
            left.ifPresent(resourceDimension -> resourceShortage.put(tier, resourceDimension));
        }
    }
    return new CapacityAllocations(instanceAllocations, resourceShortage);
}
 
源代码5 项目: hono   文件: Configurations.java
/**
 * Create a new default table configuration.
 *
 * @param jdbcUrl The JDBC URL.
 * @param tableName The optional table name.
 * @param hierarchical If the JSON store uses a hierarchical model for a flat one.
 * @return The newly created configuration.
 *
 * @throws IOException in case an IO error occurs, when reading the statement configuration.
 */
public static StatementConfiguration jsonConfiguration(final String jdbcUrl, final Optional<String> tableName, final boolean hierarchical) throws IOException {

    final String dialect = SQL.getDatabaseDialect(jdbcUrl);
    final String tableNameString = tableName.orElse(DEFAULT_TABLE_NAME_JSON);
    final String jsonModel = hierarchical ? "json.tree" : "json.flat";

    final Path base = StatementConfiguration.DEFAULT_PATH.resolve("device");

    return StatementConfiguration
            .empty(tableNameString)
            .overrideWithDefaultPattern("base", dialect, Configurations.class, base)
            .overrideWithDefaultPattern("json", dialect, Configurations.class, base)
            .overrideWithDefaultPattern(jsonModel, dialect, Configurations.class, base);

}
 
源代码6 项目: syncope   文件: JobWidget.java
@Override
@SuppressWarnings("unchecked")
public void onEvent(final IEvent<?> event) {
    if (event.getPayload() instanceof AjaxWizard.NewItemEvent) {
        Optional<AjaxRequestTarget> target = ((AjaxWizard.NewItemEvent<?>) event.getPayload()).getTarget();

        if (target.isPresent()
                && event.getPayload() instanceof AjaxWizard.NewItemCancelEvent
                || event.getPayload() instanceof AjaxWizard.NewItemFinishEvent) {

            jobModal.close(target.get());
        }
    }

    super.onEvent(event);
}
 
源代码7 项目: metron   文件: GrokWebSphereParserTest.java
@Test
public void testParseLoginLine() {
	String testString = "<133>Apr 15 17:47:28 ABCXML1413 [rojOut][0x81000033][auth][notice] user(rick007): "
			+ "[120.43.200.6]: User logged into 'cohlOut'.";
	Optional<MessageParserResult<JSONObject>> resultOptional = parser.parseOptionalResult(testString.getBytes(
       StandardCharsets.UTF_8));
	assertNotNull(resultOptional);
	assertTrue(resultOptional.isPresent());
	List<JSONObject> result = resultOptional.get().getMessages();
	JSONObject parsedJSON = result.get(0);

	long expectedTimestamp = ZonedDateTime.of(Year.now(UTC).getValue(), 4, 15, 17, 47, 28, 0, UTC).toInstant().toEpochMilli();

	//Compare fields
	assertEquals(133, parsedJSON.get("priority"));
	assertEquals(expectedTimestamp, parsedJSON.get("timestamp"));
	assertEquals("ABCXML1413", parsedJSON.get("hostname"));
	assertEquals("rojOut", parsedJSON.get("security_domain"));
	assertEquals("0x81000033", parsedJSON.get("event_code"));
	assertEquals("auth", parsedJSON.get("event_type"));
	assertEquals("notice", parsedJSON.get("severity"));
	assertEquals("login", parsedJSON.get("event_subtype"));
	assertEquals("rick007", parsedJSON.get("username"));
	assertEquals("120.43.200.6", parsedJSON.get("ip_src_addr"));
}
 
源代码8 项目: joynr   文件: ChannelRecoveryTest.java
@Test
public void testErrorHandlingBpUnreachableForClusterControllersOnly() {

    Mockito.when(mock.getChannel("channel-123"))
           .thenReturn(Optional.of(createChannel("X.Y", "http://joyn-bpX.muc/bp", "channel-123")));
    Mockito.when(mock.isBounceProxyForChannelResponding("channel-123")).thenReturn(true);

    Response response = //
            given(). //
                   queryParam("bp", "X.Y").and().queryParam("status", "unreachable").when().put(serverUrl
                           + "/channel-123");

    assertEquals(204 /* No Content */, response.getStatusCode());
    assertNull(response.getHeader("Location"));
    assertNull(response.getHeader("bp"));
    Mockito.verify(mock).getChannel("channel-123");
    Mockito.verify(mock).isBounceProxyForChannelResponding("channel-123");
    Mockito.verifyNoMoreInteractions(mock);
    Mockito.verify(notifierMock).alertBounceProxyUnreachable("channel-123",
                                                             "X.Y",
                                                             "127.0.0.1",
                                                             "Bounce Proxy unreachable for Cluster Controller");
}
 
源代码9 项目: Singularity   文件: RequestGroupResource.java
@GET
@Path("/group/{requestGroupId}")
@Operation(
  summary = "Get a specific Singularity request group by ID",
  responses = {
    @ApiResponse(
      responseCode = "404",
      description = "The specified request group was not found"
    )
  }
)
public Optional<SingularityRequestGroup> getRequestGroup(
  @Parameter(required = true, description = "The id of the request group") @PathParam(
    "requestGroupId"
  ) String requestGroupId
) {
  return requestGroupManager.getRequestGroup(requestGroupId);
}
 
@SuppressWarnings("unchecked")
@Test
public void resolveOptional() {
	MethodParameter param = initMethodParameter(3);
	Optional<Object> actual = (Optional<Object>) this.resolver
			.resolveArgument(param, new BindingContext(), this.exchange).block();

	assertNotNull(actual);
	assertFalse(actual.isPresent());

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultFormattingConversionService());
	BindingContext bindingContext = new BindingContext(initializer);

	Foo foo = new Foo();
	when(this.session.getAttribute("foo")).thenReturn(foo);
	actual = (Optional<Object>) this.resolver.resolveArgument(param, bindingContext, this.exchange).block();

	assertNotNull(actual);
	assertTrue(actual.isPresent());
	assertSame(foo, actual.get());
}
 
源代码11 项目: ethsigner   文件: ServerSideTlsAcceptanceTest.java
@Test
void clientMissingFromWhiteListCannotConnectToEthSigner() {
  ethSigner = createTlsEthSigner(cert1, cert1, cert1, cert1, 0);
  ethSigner.start();
  ethSigner.awaitStartupCompletion();

  final ClientTlsConfig clientTlsConfig = new ClientTlsConfig(cert1, cert2);
  final HttpRequest rawRequests =
      new HttpRequest(
          ethSigner.getUrl(),
          OkHttpClientHelpers.createOkHttpClient(Optional.of(clientTlsConfig)));

  final Throwable thrown = catchThrowable(() -> rawRequests.get("/upcheck"));

  assertThat(thrown.getCause()).isInstanceOf(SSLException.class);
}
 
源代码12 项目: dremio-oss   文件: DatasetConfigUpgrade.java
private DatasetConfig update(DatasetConfig datasetConfig) {
  if (datasetConfig == null) {
    return null;
  }
  final io.protostuff.ByteString schemaBytes = DatasetHelper.getSchemaBytes(datasetConfig);
  if (schemaBytes == null) {
    return null;
  }
  try {
    OldSchema oldSchema = OldSchema.getRootAsOldSchema(schemaBytes.asReadOnlyByteBuffer());
    byte[] newschemaBytes = convertFromOldSchema(oldSchema);
    datasetConfig.setRecordSchema(ByteString.copyFrom(newschemaBytes));
    return datasetConfig;
  } catch (Exception e) {
    System.out.println("Unable to update Arrow Schema for: " + PathUtils
      .constructFullPath(Optional.ofNullable(datasetConfig.getFullPathList()).orElse(Lists.newArrayList())));
    e.printStackTrace(System.out);
    return null;
  }
}
 
源代码13 项目: dremio-oss   文件: FabricServiceImpl.java
public FabricServiceImpl(
    String address,
    int initialPort,
    boolean allowPortHunting,
    int threadCount,
    BufferAllocator bootstrapAllocator,
    long reservationInBytes,
    long maxAllocationInBytes,
    int timeoutInSeconds,
    Executor rpcHandleDispatcher
) {
  this.address = address;
  this.initialPort = allowPortHunting ? initialPort + 333 : initialPort;
  this.allowPortHunting = allowPortHunting;
  this.threadCount = threadCount;
  this.bootstrapAllocator = bootstrapAllocator;
  this.reservationInBytes = reservationInBytes;
  this.maxAllocationInBytes = maxAllocationInBytes;

  rpcConfig = FabricRpcConfig.getMapping(timeoutInSeconds, rpcHandleDispatcher, Optional.empty());
}
 
源代码14 项目: ua-server-sdk   文件: StateVariableNode.java
public StateVariableNode(
        UaNodeManager nodeManager,
        NodeId nodeId,
        QualifiedName browseName,
        LocalizedText displayName,
        Optional<LocalizedText> description,
        Optional<UInteger> writeMask,
        Optional<UInteger> userWriteMask,
        DataValue value,
        NodeId dataType,
        Integer valueRank,
        Optional<UInteger[]> arrayDimensions,
        UByte accessLevel,
        UByte userAccessLevel,
        Optional<Double> minimumSamplingInterval,
        boolean historizing) {

    super(nodeManager, nodeId, browseName, displayName, description, writeMask, userWriteMask,
            value, dataType, valueRank, arrayDimensions, accessLevel, userAccessLevel, minimumSamplingInterval, historizing);
}
 
@Test
void shouldSaveScreenshotIntoDebugFolder(@TempDir File debugFolder)
{
    filesystemScreenshotDebugger.setDebugScreenshotsLocation(Optional.of(debugFolder));
    filesystemScreenshotDebugger.debug(FilesystemScreenshotDebuggerTests.class, SUFFIX,
            new BufferedImage(10, 10, 5));
    List<LoggingEvent> loggingEvents = testLogger.getLoggingEvents();
    assertThat(loggingEvents, Matchers.hasSize(1));
    LoggingEvent loggingEvent = loggingEvents.get(0);
    String message = loggingEvent.getMessage();
    assertEquals("Debug screenshot saved to {}", message);
    assertEquals(Level.DEBUG, loggingEvent.getLevel());
    assertThat(loggingEvent.getArguments().get(0).toString(), stringContainsInOrder(List.of(debugFolder.toString(),
            "FilesystemScreenshotDebuggerTests_suffix.png")));
    assertEquals(1, debugFolder.listFiles().length);
}
 
源代码16 项目: presto   文件: SetPathTask.java
@Override
public ListenableFuture<?> execute(
        SetPath statement,
        TransactionManager transactionManager,
        Metadata metadata,
        AccessControl accessControl,
        QueryStateMachine stateMachine,
        List<Expression> parameters)
{
    Session session = stateMachine.getSession();

    if (!session.getClientCapabilities().contains(ClientCapabilities.PATH.toString())) {
        throw new PrestoException(NOT_SUPPORTED, "SET PATH not supported by client");
    }

    // convert to IR before setting HTTP headers - ensures that the representations of all path objects outside the parser remain consistent
    SqlPath sqlPath = new SqlPath(Optional.of(statement.getPathSpecification().toString()));

    for (SqlPathElement element : sqlPath.getParsedPath()) {
        if (element.getCatalog().isEmpty() && session.getCatalog().isEmpty()) {
            throw semanticException(MISSING_CATALOG_NAME, statement, "Catalog must be specified for each path element when session catalog is not set");
        }

        element.getCatalog().ifPresent(catalog -> {
            String catalogName = catalog.getValue().toLowerCase(ENGLISH);
            if (metadata.getCatalogHandle(session, catalogName).isEmpty()) {
                throw new PrestoException(NOT_FOUND, "Catalog does not exist: " + catalogName);
            }
        });
    }
    stateMachine.setSetPath(sqlPath.toString());
    return immediateFuture(null);
}
 
@Test
void aggregateUpdate() {
    AggregateUpdate<Optional<UserAccountDomain>> update = new AggregateUpdate<>(
            Optional.of(new UserAccountDomain("Name", Money.valueOf("100"))),
            Sequence.first());

    byte[] serialised = serdes.aggregateUpdate().serializer().serialize(topic, update);
    AggregateUpdate<Optional<UserAccountDomain>> deserialised = serdes.aggregateUpdate().deserializer().deserialize(topic, serialised);
    assertThat(deserialised).isEqualToComparingFieldByField(update);
}
 
源代码18 项目: canvas-api   文件: AccountReaderUTest.java
@Test
public void testGetSingleAccount() throws Exception {
    String url = CanvasURLBuilder.buildCanvasUrl(baseUrl, apiVersion,"accounts/" + ROOT_ACCOUNT_ID, Collections.emptyMap());
    fakeRestClient.addSuccessResponse(url, "SampleJson/account/RootAccount.json");
    Optional<Account> optionalAccount = accountReader.getSingleAccount(ROOT_ACCOUNT_ID);
    Assert.assertTrue(optionalAccount.isPresent());
    Assert.assertEquals(new Integer(1), optionalAccount.get().getId());
}
 
@Override
public GobblinHelixJobLauncher buildJobLauncher(Properties jobProps)
    throws Exception {
  Properties combinedProps = new Properties();
  combinedProps.putAll(properties);
  combinedProps.putAll(jobProps);

  return new GobblinHelixJobLauncher(combinedProps,
      this.jobHelixManager,
      this.appWorkDir,
      this.metadataTags,
      this.jobRunningMap,
      Optional.of(this.helixMetrics));
}
 
源代码20 项目: vespa   文件: OperationHandlerImpl.java
protected BucketSpaceRoute resolveBucketSpaceRoute(Optional<String> wantedCluster,
                                                   Optional<String> wantedBucketSpace,
                                                   RestUri restUri) throws RestApiException {
    final List<ClusterDef> clusters = clusterEnumerator.enumerateClusters();
    ClusterDef clusterDef = resolveClusterDef(wantedCluster, clusters);

    String targetBucketSpace;
    if (!restUri.isRootOnly()) {
        String docType = restUri.getDocumentType();
        Optional<String> resolvedSpace = bucketSpaceResolver.clusterBucketSpaceFromDocumentType(clusterDef.getName(), docType);
        if (!resolvedSpace.isPresent()) {
            throw new RestApiException(Response.createErrorResponse(400, String.format(
                    "Document type '%s' in cluster '%s' is not mapped to a known bucket space", docType, clusterDef.getName()),
                    RestUri.apiErrorCodes.UNKNOWN_BUCKET_SPACE));
        }
        targetBucketSpace = resolvedSpace.get();
    } else {
        if (wantedBucketSpace.isPresent() && !isValidBucketSpace(wantedBucketSpace.get())) {
            // TODO enumerate known bucket spaces from a repo instead of having a fixed set
            throw new RestApiException(Response.createErrorResponse(400, String.format(
                    "Bucket space '%s' is not a known bucket space (expected '%s' or '%s')",
                    wantedBucketSpace.get(), FixedBucketSpaces.defaultSpace(), FixedBucketSpaces.globalSpace()),
                    RestUri.apiErrorCodes.UNKNOWN_BUCKET_SPACE));
        }
        targetBucketSpace = wantedBucketSpace.orElse(FixedBucketSpaces.defaultSpace());
    }

    return new BucketSpaceRoute(clusterDefToRoute(clusterDef), targetBucketSpace);
}
 
源代码21 项目: titus-control-plane   文件: KubeConstraintTest.java
@Test
public void nodeNotReady() {
    AgentInstance agentInstance = createAgentInstance(INSTANCE_ID, INSTANCE_GROUP_ID);
    when(agentManagementService.findAgentInstance(INSTANCE_ID)).thenReturn(Optional.of(agentInstance));

    V1Node node = createNode(INSTANCE_ID, false, Collections.emptyList());
    when(indexer.getByKey(INSTANCE_ID)).thenReturn(node);

    ConstraintEvaluator.Result result = kubeConstraint.evaluate(
            createTaskRequest(TASK_ID),
            createVirtualMachineCurrentStateMock(INSTANCE_ID, Collections.emptyList(), Collections.emptyList()),
            taskTrackerState);
    assertThat(result.isSuccessful()).isFalse();
    assertThat(result.getFailureReason()).isEqualToIgnoringCase(KubeConstraint.NODE_NOT_READY_REASON);
}
 
@Test
void downstreamKnownServerIsNotRequiredIfCaSignedEnabledExplicitly() {
  List<String> cmdLine =
      modifyField(validBaseCommandOptions(), "downstream-http-tls-ca-auth-enabled", "true");
  cmdLine = removeFieldsFrom(cmdLine, "downstream-http-tls-known-servers-file");
  cmdLine.add(subCommand.getCommandName());
  final boolean result = parser.parseCommandLine(cmdLine.toArray(String[]::new));

  assertThat(result).as("CLI Parse result").isTrue();
  final Optional<ClientTlsOptions> optionalDownstreamTlsOptions = config.getClientTlsOptions();
  assertThat(optionalDownstreamTlsOptions.isPresent()).as("Downstream TLS Options").isTrue();
}
 
源代码23 项目: buck   文件: TargetsCommandTest.java
@Test
public void testGetMatchingAppleLibraryBuildTarget() {
  assumeTrue(AppleNativeIntegrationTestUtils.isApplePlatformAvailable(ApplePlatform.MACOSX));
  BuildTarget libraryTarget = BuildTargetFactory.newInstance("//foo:lib");
  TargetNode<?> libraryNode =
      AppleLibraryBuilder.createBuilder(libraryTarget)
          .setSrcs(ImmutableSortedSet.of(SourceWithFlags.of(FakeSourcePath.of("foo/foo.m"))))
          .build();

  ImmutableSet<TargetNode<?>> nodes = ImmutableSet.of(libraryNode);

  TargetGraph targetGraph = TargetGraphFactory.newInstance(nodes);

  // No target depends on the referenced file.
  SortedMap<String, TargetNode<?>> matchingBuildRules =
      targetsCommand.getMatchingNodes(
          targetGraph,
          Optional.of(ImmutableSet.of(RelPath.get("foo/bar.m"))),
          Optional.empty(),
          Optional.empty(),
          false,
          "BUCK",
          filesystem);
  assertTrue(matchingBuildRules.isEmpty());

  // The AppleLibrary matches the referenced file.
  matchingBuildRules =
      targetsCommand.getMatchingNodes(
          targetGraph,
          Optional.of(ImmutableSet.of(RelPath.get("foo/foo.m"))),
          Optional.empty(),
          Optional.empty(),
          false,
          "BUCK",
          filesystem);
  assertEquals(ImmutableSet.of("//foo:lib"), matchingBuildRules.keySet());
}
 
@Override
public Optional<T> loadService() {
    return httpProviders.stream()
                        .map(SdkHttpServiceProvider::loadService)
                        .filter(Optional::isPresent)
                        .map(Optional::get)
                        .findFirst();
}
 
源代码25 项目: meghanada-server   文件: TypeScope.java
@Override
public Optional<ExpressionScope> getExpression(final int line) {
  Scope sc = getScope(line, super.scopes);
  if (nonNull(sc) && (sc instanceof BlockScope)) {
    BlockScope bs = (BlockScope) sc;
    return bs.getExpression(line);
  }
  return Optional.empty();
}
 
源代码26 项目: presto   文件: BenchmarkEqualsOperator.java
@Benchmark
public List<Page> processPage(BenchmarkData data)
{
    List<Page> output = new ArrayList<>();
    Iterator<Optional<Page>> pageProcessorOutput = compiledProcessor.process(
            SESSION,
            SIGNAL,
            newSimpleAggregatedMemoryContext().newLocalMemoryContext(PageProcessor.class.getSimpleName()),
            data.page);
    while (pageProcessorOutput.hasNext()) {
        pageProcessorOutput.next().ifPresent(output::add);
    }
    return output;
}
 
源代码27 项目: ua-server-sdk   文件: UaMethodLoader.java
private void buildNode117() {
    UaMethodNode node = new UaMethodNode(this.nodeManager, NodeId.parse("ns=0;i=2429"), new QualifiedName(0, "Halt"), new LocalizedText("en", "Halt"), Optional.of(new LocalizedText("en", "Causes the Program to transition from the Ready, Running or Suspended state to the Halted state.")), Optional.of(UInteger.valueOf(0L)), Optional.of(UInteger.valueOf(0L)), true, true);
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=47"), ExpandedNodeId.parse("svr=0;i=2391"), NodeClass.ObjectType, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=53"), ExpandedNodeId.parse("svr=0;i=2412"), NodeClass.Object, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=53"), ExpandedNodeId.parse("svr=0;i=2420"), NodeClass.Object, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=53"), ExpandedNodeId.parse("svr=0;i=2424"), NodeClass.Object, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=53"), ExpandedNodeId.parse("svr=0;i=2412"), NodeClass.Object, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=53"), ExpandedNodeId.parse("svr=0;i=2420"), NodeClass.Object, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=53"), ExpandedNodeId.parse("svr=0;i=2424"), NodeClass.Object, false));
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=37"), ExpandedNodeId.parse("svr=0;i=78"), NodeClass.Object, true));
    node.addReference(new Reference(NodeId.parse("ns=0;i=2429"), NodeId.parse("ns=0;i=47"), ExpandedNodeId.parse("svr=0;i=2391"), NodeClass.ObjectType, false));
    this.nodeManager.addNode(node);
}
 
源代码28 项目: cloudbreak   文件: AlertController.java
@Override
@CheckPermissionByAccount(action = AuthorizationResourceAction.DATAHUB_WRITE)
public TimeAlertResponse updateTimeAlert(Long clusterId, Long alertId, TimeAlertRequest json) {
    validateTimeAlert(clusterId, Optional.of(alertId), json);
    TimeAlert timeAlert = timeAlertRequestConverter.convert(json);
    return createTimeAlertResponse(alertService.updateTimeAlert(clusterId, alertId, timeAlert));
}
 
MutablePropertySources initialize(MutablePropertySources originalPropertySources) {
    InterceptionMode actualInterceptionMode = Optional.ofNullable(interceptionMode).orElse(InterceptionMode.WRAPPER);
    List<Class<PropertySource<?>>> actualSkipPropertySourceClasses = Optional.ofNullable(skipPropertySourceClasses).orElseGet(Collections::emptyList);
    EnvCopy envCopy = new EnvCopy(environment);
    EncryptablePropertyFilter actualFilter = Optional.ofNullable(filter).orElseGet(() -> new DefaultLazyPropertyFilter(envCopy.get()));
    StringEncryptor actualEncryptor = Optional.ofNullable(encryptor).orElseGet(() -> new DefaultLazyEncryptor(envCopy.get()));
    EncryptablePropertyDetector actualDetector = Optional.ofNullable(detector).orElseGet(() -> new DefaultLazyPropertyDetector(envCopy.get()));
    EncryptablePropertyResolver actualResolver = Optional.ofNullable(resolver).orElseGet(() -> new DefaultLazyPropertyResolver(actualDetector, actualEncryptor, environment));
    EncryptablePropertySourceConverter converter = new EncryptablePropertySourceConverter(actualInterceptionMode, actualSkipPropertySourceClasses, actualResolver, actualFilter);
    converter.convertPropertySources(originalPropertySources);
    return converter.proxyPropertySources(originalPropertySources, envCopy);
}
 
源代码30 项目: junit5-extensions   文件: GuiceExtension.java
/**
 * Returns an injector for the given context if and only if the given context has an {@link
 * ExtensionContext#getElement() annotated element}.
 */
private static Optional<Injector> getOrCreateInjector(ExtensionContext context)
    throws NoSuchMethodException,
    InstantiationException,
    IllegalAccessException,
    InvocationTargetException {
  if (!context.getElement().isPresent()) {
    return Optional.empty();
  }
  AnnotatedElement element = context.getElement().get();
  Store store = context.getStore(NAMESPACE);
  Injector injector = store.get(element, Injector.class);
  boolean sharedInjector = isSharedInjector(context);
  Set<Class<? extends Module>> moduleClasses = Collections.emptySet();
  if (injector == null && sharedInjector) {
    moduleClasses = getContextModuleTypes(context);
    injector = INJECTOR_CACHE.get(moduleClasses);
  }
  if (injector == null) {
    injector = createInjector(context);
    store.put(element, injector);
    if (sharedInjector && !moduleClasses.isEmpty()) {
      INJECTOR_CACHE.put(moduleClasses, injector);
    }
  }
  return Optional.of(injector);
}
 
 类所在包
 同包方法