java.util.Optional Java Examples

The following examples show how to use java.util.Optional. 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: GetChainHead.java    From teku with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #2
Source File: AzureDatabaseResourceServiceTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #3
Source File: ReporterSetup.java    From flink with Apache License 2.0 6 votes vote down vote up
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));
	}
}
 
Example #4
Source File: SimpleCapacityGuaranteeStrategy.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
Source File: Configurations.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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);

}
 
Example #6
Source File: JobWidget.java    From syncope with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #7
Source File: GrokWebSphereParserTest.java    From metron with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #8
Source File: ChannelRecoveryTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #9
Source File: RequestGroupResource.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: SessionAttributeMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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());
}
 
Example #11
Source File: ServerSideTlsAcceptanceTest.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: DatasetConfigUpgrade.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
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;
  }
}
 
Example #13
Source File: FabricServiceImpl.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #14
Source File: StateVariableNode.java    From ua-server-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
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);
}
 
Example #15
Source File: FilesystemScreenshotDebuggerTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: SetPathTask.java    From presto with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: AvroCustomAggregateSerdeTests.java    From simplesource with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #18
Source File: AccountReaderUTest.java    From canvas-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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());
}
 
Example #19
Source File: GobblinHelixJobScheduler.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #20
Source File: OperationHandlerImpl.java    From vespa with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #21
Source File: KubeConstraintTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #22
Source File: CommandlineParserClientTlsOptionsTest.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #23
Source File: TargetsCommandTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #24
Source File: SdkHttpServiceProviderChain.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<T> loadService() {
    return httpProviders.stream()
                        .map(SdkHttpServiceProvider::loadService)
                        .filter(Optional::isPresent)
                        .map(Optional::get)
                        .findFirst();
}
 
Example #25
Source File: TypeScope.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example #26
Source File: BenchmarkEqualsOperator.java    From presto with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #27
Source File: UaMethodLoader.java    From ua-server-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #28
Source File: AlertController.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #29
Source File: EnvironmentInitializer.java    From jasypt-spring-boot with MIT License 5 votes vote down vote up
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);
}
 
Example #30
Source File: GuiceExtension.java    From junit5-extensions with MIT License 5 votes vote down vote up
/**
 * 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);
}