下面列出了java.util.Optional#empty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
}
/**
* 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());
}
@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());
}
public SingularityDeployRequest(
SingularityDeploy deploy,
Optional<Boolean> unpauseOnSuccessfulDeploy,
Optional<String> message
) {
this(
deploy,
unpauseOnSuccessfulDeploy,
message,
Optional.<SingularityRequest>empty()
);
}
default Function<T, Optional<R>> lift() {
return t -> {
try {
return Optional.ofNullable(apply(t));
} catch (final Exception e) {
return Optional.empty();
}
};
}
@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());
}
};
}
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));
}
/**
* 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();
}
/**
* 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();
}
/**
* 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();
}
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);
}
public static Optional<InetAddress> getInetAddress(){
try {
return Optional.ofNullable(InetAddress.getLocalHost());
} catch (UnknownHostException e) {
return Optional.empty();
}
}
/**
* 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();
}
public Revoke(boolean grantOptionFor, Optional<List<String>> privileges, boolean table, QualifiedName tableName, Identifier grantee)
{
this(Optional.empty(), grantOptionFor, privileges, table, tableName, grantee);
}
public Optional<Object> getConfig(String name) {
return config == null ? Optional.empty() : Optional.ofNullable(config.get(name));
}
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);
}
@Override
public Optional<String> getErrorAppTag() {
return Optional.empty();
}
@Override
public Optional<SourcePath> getPrecompiledHeader() {
return Optional.empty();
}
/**
* 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));
}
/**
* 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());
}