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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #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: 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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
Source File: UserService.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Optional<Account> verify(String email, String token) {
    Optional<Account> optionalAcct= accountDAO.accountByEmail(email);
    if(optionalAcct.isPresent()) {
        Account acct = optionalAcct.get();
        if(acct.getPassword().equals(token)) {
            accountDAO.activateAccount(acct.getName());
            return Optional.of(acct);
        }
    }
    return Optional.empty();
}
 
Example #21
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);
}
 
Example #22
Source File: Serializer.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Double> deserialize(JsonNode json) {
    if (json instanceof DoubleNode || json instanceof FloatNode) {
        return Optional.of(json.asDouble());
    } else {
        return Optional.empty();
    }
}
 
Example #23
Source File: DefaultDebugFlow.java    From dew with Apache License 2.0 5 votes vote down vote up
@Override
protected void process(FinalProjectConfig config, String flowBasePath) throws ApiException, IOException {
    final Signal sig = new Signal(getOSSignalType());
    podName = PodSelector.select(config, Optional.ofNullable(podName));
    KubeHelper.inst(config.getId())
            .exec(podName, KubeDeploymentBuilder.FLAG_CONTAINER_NAME, config.getNamespace(),
                    new String[]{
                            "./debug-java.sh"
                    }, System.out::println);
    V1Service service = KubeHelper.inst(config.getId()).read(config.getAppName(), config.getNamespace(), KubeRES.SERVICE, V1Service.class);
    new KubeServiceBuilder().buildDebugPort(service, config.getApp().getDebugPort(), 5005);
    KubeHelper.inst(config.getId()).replace(service);
    service = KubeHelper.inst(config.getId()).read(config.getAppName(), config.getNamespace(), KubeRES.SERVICE, V1Service.class);
    System.out.println("Http-debug nodePort:["
            + service.getSpec().getPorts().stream().filter(v1ServicePort -> v1ServicePort.getPort().equals(5005))
            .map(V1ServicePort::getNodePort).collect(Collectors.toList()).get(0)
            + "].   Http-new nodePort: [" + service.getSpec().getPorts().stream().filter(v1ServicePort -> v1ServicePort.getPort().equals(9000))
            .map(V1ServicePort::getNodePort).collect(Collectors.toList()).get(0) + "]");
    System.out.println("==================\n"
            + "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005\n"
            + "==================");
    Signal.handle(sig, new ShutdownHandler(service, config));
    try {
        // 等待手工停止
        new CountDownLatch(1).await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
Example #24
Source File: StreamProcessor.java    From samza with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
SamzaContainer createSamzaContainer(String processorId, JobModel jobModel) {

  // Creating diagnostics manager and reporter, and wiring it respectively
  String jobName = new JobConfig(config).getName().get();
  String jobId = new JobConfig(config).getJobId();
  Optional<Pair<DiagnosticsManager, MetricsSnapshotReporter>> diagnosticsManagerReporterPair =
      DiagnosticsUtil.buildDiagnosticsManager(jobName, jobId, jobModel, processorId, Optional.empty(), config);
  Option<DiagnosticsManager> diagnosticsManager = Option.empty();
  if (diagnosticsManagerReporterPair.isPresent()) {
    diagnosticsManager = Option.apply(diagnosticsManagerReporterPair.get().getKey());
    this.customMetricsReporter.put(MetricsConfig.METRICS_SNAPSHOT_REPORTER_NAME_FOR_DIAGNOSTICS, diagnosticsManagerReporterPair.get().getValue());
  }

  // Metadata store lifecycle managed outside of the SamzaContainer.
  // All manager lifecycles are managed in the SamzaContainer including startpointManager
  StartpointManager startpointManager = null;
  if (metadataStore != null && new JobConfig(config).getStartpointEnabled()) {
    startpointManager = new StartpointManager(metadataStore);
  } else if (!new JobConfig(config).getStartpointEnabled()) {
    LOGGER.warn("StartpointManager not instantiated because startpoints is not enabled");
  } else {
    LOGGER.warn("StartpointManager cannot be instantiated because no metadata store defined for this stream processor");
  }

  return SamzaContainer.apply(processorId, jobModel, ScalaJavaUtil.toScalaMap(this.customMetricsReporter),
      this.taskFactory, JobContextImpl.fromConfigWithDefaults(this.config),
      Option.apply(this.applicationDefinedContainerContextFactoryOptional.orElse(null)),
      Option.apply(this.applicationDefinedTaskContextFactoryOptional.orElse(null)),
      Option.apply(this.externalContextOptional.orElse(null)), null, startpointManager,
      diagnosticsManager);
}
 
Example #25
Source File: ZonkyPostgresDatabaseProvider.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
public ZonkyPostgresDatabaseProvider(Environment environment, ObjectProvider<List<Consumer<EmbeddedPostgres.Builder>>> databaseCustomizers) {
    String preparerIsolation = environment.getProperty("zonky.test.database.postgres.zonky-provider.preparer-isolation", "database");
    PreparerIsolation isolation = PreparerIsolation.valueOf(preparerIsolation.toUpperCase());

    Map<String, String> initdbProperties = PropertyUtils.extractAll(environment, "zonky.test.database.postgres.initdb.properties");
    Map<String, String> configProperties = PropertyUtils.extractAll(environment, "zonky.test.database.postgres.server.properties");
    Map<String, String> connectProperties = PropertyUtils.extractAll(environment, "zonky.test.database.postgres.client.properties");

    List<Consumer<EmbeddedPostgres.Builder>> customizers = Optional.ofNullable(databaseCustomizers.getIfAvailable()).orElse(emptyList());

    this.databaseConfig = new DatabaseConfig(initdbProperties, configProperties, customizers, isolation);
    this.clientConfig = new ClientConfig(connectProperties);
}
 
Example #26
Source File: CreatePrescriptionHelper.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
public void createPrescription(){
	Optional<IArticleDefaultSignature> defaultSignature =
		MedicationServiceHolder.get().getDefaultSignature(article);
	
	Optional<IArticleDefaultSignature> signature = Optional.empty();
	if (defaultSignature.isPresent()) {
		signature = defaultSignature;
		if (CoreHub.userCfg.get(MEDICATION_SETTINGS_ALWAYS_SHOW_SIGNATURE_DIALOG, false)) {
			signature = getSignatureWithDialog(defaultSignature);
		}
	} else {
		signature = getSignatureWithDialog(Optional.empty());
	}
	signature.ifPresent(s -> createPrescriptionFromSignature(s));
}
 
Example #27
Source File: BuckBuildUtil.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Get the value of a named property in a specific buck rule body. */
public static String getPropertyStringValue(BuckFunctionTrailer functionTrailer, String name) {
  return Optional.ofNullable(functionTrailer.getNamedArgument(name))
      .map(BuckArgument::getExpression)
      .map(BuckExpression::getStringValue)
      .orElse(null);
}
 
Example #28
Source File: ContainerManager.java    From samza with Apache License 2.0 5 votes vote down vote up
/**
 * Handles an expired resource request for both active and standby containers.
 *
 * Case 1. If this expired request is due to a container placement action mark the request as failed and return
 * Case 2: Otherwise for a normal resource request following cases are possible
 *    Case 2.1  If StandbyContainer is present refer to {@code StandbyContainerManager#handleExpiredResourceRequest}
 *    Case 2.2: host-affinity is enabled, allocator thread looks for allocated resources on ANY_HOST and issues a
 *              container start if available, otherwise issue an ANY_HOST request
 *    Case 2.2: host-affinity is disabled, allocator thread does not handle expired requests, it waits for cluster
 *              manager to return resources on ANY_HOST
 *
 * @param processorId logical id of the container
 * @param preferredHost host on which container is requested to be deployed
 * @param request pending request for the preferred host
 * @param allocator allocator for requesting resources
 * @param resourceRequestState state of request in {@link ContainerAllocator}
 */
@VisibleForTesting
void handleExpiredRequest(String processorId, String preferredHost,
    SamzaResourceRequest request, ContainerAllocator allocator, ResourceRequestState resourceRequestState) {
  boolean resourceAvailableOnAnyHost = allocator.hasAllocatedResource(ResourceRequestState.ANY_HOST);


  // Case 1. Container placement actions can be taken in either cases of host affinity being set, in both cases
  // mark the container placement action failed
  if (hasActiveContainerPlacementAction(processorId)) {
    resourceRequestState.cancelResourceRequest(request);
    markContainerPlacementActionFailed(getPlacementActionMetadata(processorId).get(),
        "failed the ContainerPlacement action because request for resources to ClusterManager expired");
    return;
  }

  // Case 2. When host affinity is disabled wait for cluster resource manager return resources
  // TODO: SAMZA-2330: Handle expired request for host affinity disabled case by retying request for getting ANY_HOST
  if (!hostAffinityEnabled) {
    return;
  }

  // Case 2. When host affinity is enabled handle the expired requests
  if (standbyContainerManager.isPresent()) {
    standbyContainerManager.get()
        .handleExpiredResourceRequest(processorId, request,
            Optional.ofNullable(allocator.peekAllocatedResource(ResourceRequestState.ANY_HOST)), allocator,
            resourceRequestState);
  } else if (resourceAvailableOnAnyHost) {
    LOG.info("Request for Processor ID: {} on host: {} has expired. Running on ANY_HOST", processorId, preferredHost);
    allocator.runStreamProcessor(request, ResourceRequestState.ANY_HOST);
  } else {
    LOG.info("Request for Processor ID: {} on host: {} has expired. Requesting additional resources on ANY_HOST.",
        processorId, preferredHost);
    resourceRequestState.cancelResourceRequest(request);
    allocator.requestResource(processorId, ResourceRequestState.ANY_HOST);
  }
}
 
Example #29
Source File: CxxDescriptionEnhancer.java    From buck with Apache License 2.0 5 votes vote down vote up
public static String getStaticLibraryName(
    BuildTarget target,
    Optional<String> staticLibraryBasename,
    String extension,
    boolean uniqueLibraryNameEnabled) {
  return getStaticLibraryName(
      target, staticLibraryBasename, extension, "", uniqueLibraryNameEnabled);
}
 
Example #30
Source File: ResponseHandlerTest.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
@Test
public void itDoesNotPasExceptionsToTheProvidedHandlerIfThereIsAPendingFuture() throws Exception {
  Consumer<Throwable> exceptionHandler = (Consumer<Throwable>) mock(Consumer.class);
  ResponseHandler responseHandler = new ResponseHandler(CONNECTION_ID, Optional.empty(), Optional.of(exceptionHandler));

  responseHandler.createResponseFuture(1, DEBUG_STRING);

  Exception testException = new Exception("oh no");
  responseHandler.exceptionCaught(null, testException);

  verify(exceptionHandler, never()).accept(testException);
}