Java Code Examples for java.util.Optional#empty()

The following examples show how to use java.util.Optional#empty() . 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: AccountDAOJdbcImpl.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Optional<Account> accountByUsername(String name) {
    try(Connection conn = dataSource.getConnection();
            PreparedStatement stmt = conn.prepareStatement(
                    "SELECT * FROM t_account WHERE name = ?")) {
        stmt.setString(1, name);
        ResultSet rs = stmt.executeQuery();
        if(rs.next()) {
            return Optional.of(new Account(
                rs.getString(1),
                rs.getString(2),
                rs.getString(3),
                rs.getString(4)
            ));
        } else {
            return Optional.empty();
        }

    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: SdkHttpUtils.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * Flatten the provided query parameters into a string that can be used as the query string in a URL. The result is not
 * prepended with "?". This is useful when you have already-encoded query parameters you wish to flatten.
 */
public static Optional<String> flattenQueryParameters(Map<String, List<String>> toFlatten) {
    if (toFlatten.isEmpty()) {
        return Optional.empty();
    }

    StringBuilder result = new StringBuilder();

    for (Entry<String, List<String>> encodedQueryParameter : toFlatten.entrySet()) {
        String key = encodedQueryParameter.getKey();

        List<String> values = Optional.ofNullable(encodedQueryParameter.getValue()).orElseGet(Collections::emptyList);

        for (String value : values) {
            if (result.length() > 0) {
                result.append('&');
            }
            result.append(key);
            if (value != null) {
                result.append('=');
                result.append(value);
            }
        }
    }
    return Optional.of(result.toString());
}
 
Example 3
Source File: SingularityDeployRequest.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public SingularityDeployRequest(
  SingularityDeploy deploy,
  Optional<Boolean> unpauseOnSuccessfulDeploy,
  Optional<String> message
) {
  this(
    deploy,
    unpauseOnSuccessfulDeploy,
    message,
    Optional.<SingularityRequest>empty()
  );
}
 
Example 4
Source File: ThrowingFunction.java    From throwing-function with Apache License 2.0 5 votes vote down vote up
default Function<T, Optional<R>> lift() {
    return t -> {
        try {
            return Optional.ofNullable(apply(t));
        } catch (final Exception e) {
            return Optional.empty();
        }
    };
}
 
Example 5
Source File: ReductionDriverTest.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
@Test
public void testReductionOfUnreferencedUniform() throws Exception {

  // Check that a shader job with metadata for one unreferenced uniform gets
  // reduced to a shader job with no metadata for uniforms.

  final String emptyShader = "void main() { }";
  final TranslationUnit fragShader = ParseHelper.parse(emptyShader);
  final PipelineInfo pipelineInfo = new PipelineInfo();
  pipelineInfo.addUniform("a", BasicType.FLOAT, Optional.empty(), Collections.singletonList(1.0));
  final ShaderJob shaderJob = new GlslShaderJob(Optional.empty(),
      pipelineInfo,
      fragShader);
  assertEquals(1, shaderJob.getPipelineInfo().getNumUniforms());

  final File workDir = testFolder.getRoot();
  final File tempShaderJobFile = new File(workDir, "temp.json");
  fileOps.writeShaderJobFile(shaderJob, tempShaderJobFile);

  final String resultsPrefix = new ReductionDriver(new ReducerContext(true,
      ShadingLanguageVersion.ESSL_100,
      new RandomWrapper(0),
      new IdGenerator()),
      false,
      fileOps,
      (unused, item) -> true, workDir)
      .doReduction(shaderJob, "temp", 0, 100);

  final ShaderJob after = fileOps.readShaderJobFile(new File(testFolder.getRoot(),
      resultsPrefix + ".json"));

  CompareAsts.assertEqualAsts(emptyShader,
      after.getFragmentShader().get());
  assertEquals(0, after.getPipelineInfo().getNumUniforms());

}
 
Example 6
Source File: DataGeneratorSource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public Record<Person> read() throws Exception {
    Thread.sleep(50);
    return new Record<Person>() {
        @Override
        public Optional<String> getKey() {
            return Optional.empty();
        }

        @Override
        public Person getValue() {
            return new Person(fairy.person());
        }
    };
}
 
Example 7
Source File: CurrentPositionCharacteristic.java    From HAP-Java with MIT License 5 votes vote down vote up
public CurrentPositionCharacteristic(
    Supplier<CompletableFuture<Integer>> getter,
    Consumer<HomekitCharacteristicChangeCallback> subscriber,
    Runnable unsubscriber) {
  super(
      "0000006D-0000-1000-8000-0026BB765291",
      "current position",
      0,
      100,
      "%",
      Optional.of(getter),
      Optional.empty(),
      Optional.of(subscriber),
      Optional.of(unsubscriber));
}
 
Example 8
Source File: ModelConverterRegistrar.java    From springdoc-openapi with Apache License 2.0 5 votes vote down vote up
/**
 * Gets registered converter same as.
 *
 * @param modelConverter the model converter
 * @return the registered converter same as
 */
private Optional<ModelConverter> getRegisteredConverterSameAs(ModelConverter modelConverter) {
	try {
		Field convertersField = FieldUtils.getDeclaredField(ModelConverters.class, "converters", true);
		List<ModelConverter> modelConverters = (List<ModelConverter>) convertersField.get(modelConvertersInstance);
		return modelConverters.stream()
				.filter(registeredModelConverter -> isSameConverter(registeredModelConverter, modelConverter))
				.findFirst();
	}
	catch (IllegalAccessException exception) {
		LOGGER.warn(exception.getMessage());
	}
	return Optional.empty();
}
 
Example 9
Source File: JsonUtil.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a string array.
 * 
 * @param node the json node
 * @return List of strings
 */
public static Optional<List<String>> readStringArray(final JsonNode node) {
    if (node != null && node.isArray()) {

        List<String> rval = new ArrayList<>(node.size());
        ArrayNode arrayNode = (ArrayNode) node;
        for (JsonNode arrayItem : arrayNode) {
            if (arrayItem != null) {
                rval.add(arrayItem.asText());
            }
        }
        return Optional.of(rval);
    }
    return Optional.empty();
}
 
Example 10
Source File: LogUtil.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Gets the {@code correlationId} from the default slf4j {@link org.slf4j.MDC}.
 *
 * @return the {@code correlationId} from {@link org.slf4j.MDC} or an empty {@link java.util.Optional} if it didn't exist.
 */
public static Optional<String> getCorrelationId() {
    final String correlationId = MDC.get(X_CORRELATION_ID);
    if (null != correlationId) {
        return Optional.of(correlationId);
    }
    return Optional.empty();
}
 
Example 11
Source File: TagReader.java    From smallrye-open-api with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a list of {@link Tag} OpenAPI nodes.
 * 
 * @param node the json array node
 * @return List of Tag models
 */
public static Optional<List<Tag>> readTags(final JsonNode node) {
    if (node != null && node.isArray()) {
        IoLogging.log.jsonArray("Tag");
        ArrayNode nodes = (ArrayNode) node;
        List<Tag> rval = new ArrayList<>(nodes.size());
        for (JsonNode tagNode : nodes) {
            rval.add(readTag(tagNode));
        }
        return Optional.of(rval);
    }
    return Optional.empty();
}
 
Example 12
Source File: NetUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static Optional<InetAddress> getInetAddress(){
	try {
		return Optional.ofNullable(InetAddress.getLocalHost());
	} catch (UnknownHostException e) {
		return Optional.empty();
	}
}
 
Example 13
Source File: TestHivePageSink.java    From presto with Apache License 2.0 5 votes vote down vote up
private static ConnectorPageSink createPageSink(HiveTransactionHandle transaction, HiveConfig config, HiveMetastore metastore, Path outputPath, HiveWriterStats stats)
{
    ConnectorSession session = getHiveSession(config);
    HiveIdentity identity = new HiveIdentity(session);
    LocationHandle locationHandle = new LocationHandle(outputPath, outputPath, false, DIRECT_TO_TARGET_NEW_DIRECTORY);
    HiveOutputTableHandle handle = new HiveOutputTableHandle(
            SCHEMA_NAME,
            TABLE_NAME,
            getColumnHandles(),
            new HivePageSinkMetadata(new SchemaTableName(SCHEMA_NAME, TABLE_NAME), metastore.getTable(identity, SCHEMA_NAME, TABLE_NAME), ImmutableMap.of()),
            locationHandle,
            config.getHiveStorageFormat(),
            config.getHiveStorageFormat(),
            ImmutableList.of(),
            Optional.empty(),
            "test",
            ImmutableMap.of(),
            false);
    JsonCodec<PartitionUpdate> partitionUpdateCodec = JsonCodec.jsonCodec(PartitionUpdate.class);
    HivePageSinkProvider provider = new HivePageSinkProvider(
            getDefaultHiveFileWriterFactories(config, HDFS_ENVIRONMENT),
            HDFS_ENVIRONMENT,
            PAGE_SORTER,
            metastore,
            new GroupByHashPageIndexerFactory(new JoinCompiler(createTestMetadataManager())),
            TYPE_MANAGER,
            config,
            new HiveLocationService(HDFS_ENVIRONMENT),
            partitionUpdateCodec,
            new TestingNodeManager("fake-environment"),
            new HiveEventClient(),
            getHiveSessionProperties(config),
            stats);
    return provider.createPageSink(transaction, getHiveSession(config), handle);
}
 
Example 14
Source File: CxxConstructorArgTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public Optional<SourcePath> getPrecompiledHeader() {
  return Optional.empty();
}
 
Example 15
Source File: BaseDecimalType.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Optional<String> getErrorAppTag() {
    return Optional.empty();
}
 
Example 16
Source File: AbstractMinMaxAggregationFunction.java    From presto with Apache License 2.0 4 votes vote down vote up
protected InternalAggregationFunction generateAggregation(Type type, MethodHandle compareMethodHandle)
{
    DynamicClassLoader classLoader = new DynamicClassLoader(AbstractMinMaxAggregationFunction.class.getClassLoader());

    List<Type> inputTypes = ImmutableList.of(type);

    MethodHandle inputFunction;
    MethodHandle combineFunction;
    MethodHandle outputFunction;
    Class<? extends AccumulatorState> stateInterface;
    AccumulatorStateSerializer<?> stateSerializer;

    if (type.getJavaType() == long.class) {
        stateInterface = NullableLongState.class;
        stateSerializer = StateCompiler.generateStateSerializer(stateInterface, classLoader);
        inputFunction = LONG_INPUT_FUNCTION.bindTo(compareMethodHandle);
        combineFunction = LONG_COMBINE_FUNCTION.bindTo(compareMethodHandle);
        outputFunction = LONG_OUTPUT_FUNCTION.bindTo(type);
    }
    else if (type.getJavaType() == double.class) {
        stateInterface = NullableDoubleState.class;
        stateSerializer = StateCompiler.generateStateSerializer(stateInterface, classLoader);
        inputFunction = DOUBLE_INPUT_FUNCTION.bindTo(compareMethodHandle);
        combineFunction = DOUBLE_COMBINE_FUNCTION.bindTo(compareMethodHandle);
        outputFunction = DOUBLE_OUTPUT_FUNCTION.bindTo(type);
    }
    else if (type.getJavaType() == boolean.class) {
        stateInterface = NullableBooleanState.class;
        stateSerializer = StateCompiler.generateStateSerializer(stateInterface, classLoader);
        inputFunction = BOOLEAN_INPUT_FUNCTION.bindTo(compareMethodHandle);
        combineFunction = BOOLEAN_COMBINE_FUNCTION.bindTo(compareMethodHandle);
        outputFunction = BOOLEAN_OUTPUT_FUNCTION.bindTo(type);
    }
    else {
        // native container type is Slice or Block
        stateInterface = BlockPositionState.class;
        stateSerializer = new BlockPositionStateSerializer(type);
        inputFunction = min ? BLOCK_POSITION_MIN_INPUT_FUNCTION.bindTo(type) : BLOCK_POSITION_MAX_INPUT_FUNCTION.bindTo(type);
        combineFunction = min ? BLOCK_POSITION_MIN_COMBINE_FUNCTION.bindTo(type) : BLOCK_POSITION_MAX_COMBINE_FUNCTION.bindTo(type);
        outputFunction = BLOCK_POSITION_OUTPUT_FUNCTION.bindTo(type);
    }

    AccumulatorStateFactory<?> stateFactory = StateCompiler.generateStateFactory(stateInterface, classLoader);

    Type intermediateType = stateSerializer.getSerializedType();
    String name = getFunctionMetadata().getSignature().getName();
    AggregationMetadata metadata = new AggregationMetadata(
            generateAggregationName(name, type.getTypeSignature(), inputTypes.stream().map(Type::getTypeSignature).collect(toImmutableList())),
            createParameterMetadata(type),
            inputFunction,
            Optional.empty(),
            combineFunction,
            outputFunction,
            ImmutableList.of(new AccumulatorStateDescriptor(
                    stateInterface,
                    stateSerializer,
                    stateFactory)),
            type);

    GenericAccumulatorFactoryBinder factory = AccumulatorCompiler.generateAccumulatorFactoryBinder(metadata, classLoader);
    return new InternalAggregationFunction(name, inputTypes, ImmutableList.of(intermediateType), type, true, false, factory);
}
 
Example 17
Source File: CandidateDimensionParserStrategy.java    From hsweb-framework with Apache License 2.0 4 votes vote down vote up
public Optional<Object> getConfig(String name) {
    return config == null ? Optional.empty() : Optional.ofNullable(config.get(name));
}
 
Example 18
Source File: Revoke.java    From rainbow with Apache License 2.0 4 votes vote down vote up
public Revoke(boolean grantOptionFor, Optional<List<String>> privileges, boolean table, QualifiedName tableName, Identifier grantee)
{
    this(Optional.empty(), grantOptionFor, privileges, table, tableName, grantee);
}
 
Example 19
Source File: RouteParameters.java    From flow with Apache License 2.0 3 votes vote down vote up
/**
 * Gets the int representation of a parameter.
 *
 * @param parameterName
 *            the name of the parameter.
 * @return an {@link Optional} {@link Integer} representation of the
 *         parameter. If the value is missing the {@link Optional} is empty.
 * @exception NumberFormatException
 *                if the value cannot be parsed as an Integer.
 */
public Optional<Integer> getInteger(String parameterName) {
    final String value = getValue(parameterName);
    if (value == null) {
        return Optional.empty();
    }

    return Optional.of(Integer.valueOf(value));
}
 
Example 20
Source File: KeyPair.java    From symbol-sdk-java with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a pair that only holds a public key using the default engine. It is good to encrypt
 * but cannot decrypt values.
 *
 * @param publicKey The public key.
 * @return a {@link KeyPair} with just the public key.
 */
public static KeyPair onlyPublic(final PublicKey publicKey) {
    return new KeyPair(Optional.empty(), publicKey, CryptoEngines.defaultEngine());
}