下面列出了java.util.Optional#equals ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void deleteScript(final String fileName, final AttributeCalculatorPane acp) {
File f = new File(fileName);
if (f.getPath().contains("_inbuilt_script")) {
final NotifyDescriptor nd = new NotifyDescriptor.Message("Can't delete inbuilt script.", NotifyDescriptor.ERROR_MESSAGE);
DialogDisplayer.getDefault().notify(nd);
} else {
final String msg = String.format("Are you sure you want to delete '%s'?",
FilenameEncoder.decode(f.getName().substring(0, f.getName().length() - 5)));
final Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setHeaderText("Delete?");
alert.setContentText(msg);
final Optional<ButtonType> action = alert.showAndWait();
final boolean del = action.equals(ButtonType.YES);
if (del) {
final boolean fIsDeleted = f.delete();
if (!fIsDeleted) {
//TODO: Handle case where file not successfully deleted
}
}
}
}
@Override
public Optional<ConstraintApplicationResult<ConnectorTableHandle>> applyFilter(ConnectorSession session, ConnectorTableHandle handle, Constraint constraint)
{
InformationSchemaTableHandle table = (InformationSchemaTableHandle) handle;
Optional<Set<String>> roles = table.getRoles();
Optional<Set<String>> grantees = table.getGrantees();
if (ROLE_AUTHORIZATION_DESCRIPTORS.equals(table.getTable()) && table.getRoles().isEmpty() && table.getGrantees().isEmpty()) {
roles = calculateRoles(session, constraint.getSummary(), constraint.predicate());
grantees = calculateGrantees(session, constraint.getSummary(), constraint.predicate());
}
Set<QualifiedTablePrefix> prefixes = table.getPrefixes();
if (isTablesEnumeratingTable(table.getTable()) && table.getPrefixes().equals(defaultPrefixes(catalogName))) {
prefixes = getPrefixes(session, table, constraint);
}
if (roles.equals(table.getRoles()) && grantees.equals(table.getGrantees()) && prefixes.equals(table.getPrefixes())) {
return Optional.empty();
}
table = new InformationSchemaTableHandle(table.getCatalogName(), table.getTable(), prefixes, roles, grantees, table.getLimit());
return Optional.of(new ConstraintApplicationResult<>(table, constraint.getSummary()));
}
@Override
public void readFrom(final UnaryOperator<String> reader) {
final Span span = activeSpan();
final Optional<FlowId> now = extractor.extract(span, reader);
final Optional<FlowId> later = extractor.extract(span);
final Optional<String> nowId = now.map(FlowId::getValue);
final Optional<String> laterId = later.map(FlowId::getValue);
if (nowId.equals(laterId)) {
later.ifPresent(flowId -> {
listener.onRead(span, flowId);
});
} else {
now.ifPresent(flowId -> {
bag(span, flowId);
listener.onRead(span, flowId);
});
}
}
private void integrityCheck(List<T> foundItems, Optional<Serializable> id, Field field, Object prop) {
if (!foundItems.isEmpty()) {
if (foundItems.size() > 1) {
throw new ElepyException(String.format("There are duplicates with the %s: '%s' in the given array!", ReflectionUtils.getPrettyName(field), String.valueOf(prop)));
}
T foundRecord = foundItems.get(0);
final Optional<Serializable> foundId = ReflectionUtils.getId(foundRecord);
if (id.isPresent() || foundId.isPresent()) {
if (!id.equals(foundId)) {
throw new ElepyException(String.format("An item with the %s: '%s' already exists in the system!", ReflectionUtils.getPrettyName(field), String.valueOf(prop)));
}
} else {
throw new ElepyException(String.format("There are duplicates with the %s: '%s' in the given array!", ReflectionUtils.getPrettyName(field), String.valueOf(prop)));
}
}
}
@VisibleForTesting
static Optional<String> getCommonProjectPrefix(ImmutableSet<String> buildTargets) {
Optional<String> commonPrefix = Optional.empty();
for (String buildTarget : buildTargets) {
Optional<String> prefix = getTargetPrefix(buildTarget);
if (!prefix.isPresent()) {
// This target did not have a prefix, so there is no common prefix
return Optional.empty();
}
if (!commonPrefix.isPresent()) {
// This is the first target, all others should match
commonPrefix = prefix;
} else if (!commonPrefix.equals(prefix)) {
// Mismatch was found
return Optional.empty();
}
}
// There was a common prefix (or buildTargets Set was empty).
return commonPrefix;
}
@Override
public Optional<? extends Module> findModule(final String name, final Optional<Revision> revision) {
for (final Module module : getNameToModules().get(name)) {
if (revision.equals(module.getRevision())) {
return Optional.of(module);
}
}
return Optional.empty();
}
private TypeCompatibility typeCompatibilityForRow(RowType firstType, RowType secondType)
{
List<Field> firstFields = firstType.getFields();
List<Field> secondFields = secondType.getFields();
if (firstFields.size() != secondFields.size()) {
return TypeCompatibility.incompatible();
}
ImmutableList.Builder<Field> fields = ImmutableList.builder();
boolean coercible = true;
for (int i = 0; i < firstFields.size(); i++) {
Type firstFieldType = firstFields.get(i).getType();
Type secondFieldType = secondFields.get(i).getType();
TypeCompatibility typeCompatibility = compatibility(firstFieldType, secondFieldType);
if (!typeCompatibility.isCompatible()) {
return TypeCompatibility.incompatible();
}
Type commonParameterType = typeCompatibility.getCommonSuperType();
Optional<String> firstParameterName = firstFields.get(i).getName();
Optional<String> secondParameterName = secondFields.get(i).getName();
Optional<String> commonName = firstParameterName.equals(secondParameterName) ? firstParameterName : Optional.empty();
// ignore parameter name for coercible
coercible &= typeCompatibility.isCoercible();
fields.add(new Field(commonName, commonParameterType));
}
return TypeCompatibility.compatible(RowType.from(fields.build()), coercible);
}
private static void assertEqualIpAddresses(HostName hostName, Optional<? extends InetAddress> resolvedAddress,
Set<String> nrAddresses, IPVersion ipVersion) {
Optional<InetAddress> nrAddress = nrAddresses.stream()
.map(InetAddresses::forString)
.filter(ipVersion::match)
.findFirst();
if (resolvedAddress.equals(nrAddress)) return;
throw new ConvergenceException(String.format(
"IP address (%s) resolved from %s does not match IP address (%s) in node-repo",
resolvedAddress.map(InetAddresses::toAddrString).orElse("[none]"), hostName,
nrAddress.map(InetAddresses::toAddrString).orElse("[none]")));
}
private static void testVersion() {
Version current = Runtime.version();
String javaVer = System.getProperty("java.runtime.version");
// java.runtime.version == $VNUM(\-$PRE)?(\+$BUILD)?(-$OPT)?
String [] jv = javaVer.split("\\+");
String [] ver = jv[0].split("-");
List<Integer> javaVerVNum
= Arrays.stream(ver[0].split("\\."))
.map(Integer::parseInt)
.collect(Collectors.toList());
if (!javaVerVNum.equals(current.version())) {
fail("Runtime.version()", javaVerVNum.toString(),
current.version().toString());
} else {
pass();
}
Optional<String> javaVerPre
= (ver.length == 2)
? Optional.ofNullable(ver[1])
: Optional.empty();
if (!javaVerPre.equals(current.pre())) {
fail("testCurrent() pre()", javaVerPre.toString(),
current.pre().toString());
} else {
pass();
}
testEHC(current.toString(), javaVer, true, true, 0, 0);
}
private void updateRegion(CharID id)
{
RegionCacheInfo rci = getInfo(id);
Optional<Region> current = rci.cachedRegion;
Optional<Region> newRegion = getRegion(id);
if (current.isEmpty() || !current.equals(newRegion))
{
current.ifPresent(region -> fireDataFacetChangeEvent(id, region.toString(), DataFacetChangeEvent.DATA_REMOVED));
rci.cachedRegion = newRegion;
fireDataFacetChangeEvent(id, newRegion.get().toString(), DataFacetChangeEvent.DATA_ADDED);
}
}
Optional<MapDifference<String, String>> invalidateIfEnvHasChanged(Cell cell, AbsPath buildFile) {
// Invalidate if env vars have changed.
ImmutableMap<String, Optional<String>> usedEnv;
try (AutoCloseableLock readLock = cachesLock.readLock()) {
usedEnv = buildFileEnv.get(buildFile);
}
if (usedEnv == null) {
this.cell.set(cell);
return Optional.empty();
}
for (Map.Entry<String, Optional<String>> ent : usedEnv.entrySet()) {
Optional<String> value =
Optional.ofNullable(cell.getBuckConfig().getEnvironment().get(ent.getKey()));
if (!value.equals(ent.getValue())) {
LOG.verbose("invalidating for env change: %s (%s != %s)", buildFile, value, ent.getValue());
invalidatePath(buildFile);
this.cell.set(cell);
return Optional.of(
Maps.difference(
value.map(v -> ImmutableMap.of(ent.getKey(), v)).orElse(ImmutableMap.of()),
ent.getValue()
.map(v -> ImmutableMap.of(ent.getKey(), v))
.orElse(ImmutableMap.of())));
}
}
return Optional.empty();
}
@Override
public void close() {
Instant lastOldestResultReceivedAt = Instant.now();
Optional<String> oldestIncompleteId = operationProcessor.oldestIncompleteResultId();
while (oldestIncompleteId.isPresent() && waitForOperations(lastOldestResultReceivedAt, sleepTimeMs, closeTimeoutMs)) {
Optional<String> oldestIncompleteIdNow = operationProcessor.oldestIncompleteResultId();
if ( ! oldestIncompleteId.equals(oldestIncompleteIdNow))
lastOldestResultReceivedAt = Instant.now();
oldestIncompleteId = oldestIncompleteIdNow;
}
operationProcessor.close();
}
/**
* In cases when performing restore and a component has been deleted, it is possible
* for existing assets to become orphaned during the restore process. In the context
* of the restore process, this method determines if an asset is associated with the
* component found (using coordinates from the restored data) using the component's entity id.
*/
private boolean assetIsAssociatedWithComponent(final T data,
final Repository repository,
final String name) throws IOException
{
Optional<EntityId> componentEntityId = componentEntityId(data);
return componentEntityId.isPresent() && componentEntityId.equals(assetComponentEntityId(repository, name));
}
private Optional<RowColumn> deleteBatch(TransactionBase tx, Optional<String> nodeId, Span span, Column column, int batchSize) {
log.trace("Deleting batch of size: " + batchSize + " using Span: " + span + " and Column: " + column);
RowScanner rs = tx.scanner().over(span).fetch(column).byRow().build();
try {
Iterator<ColumnScanner> colScannerIter = rs.iterator();
int count = 0;
boolean batchLimitMet = false;
Bytes row = span.getStart().getRow();
//get prefix if nodeId is specified
Optional<Bytes> prefixBytes = Optional.empty();
if (nodeId.isPresent()) {
NodeType type = NodeType.fromNodeId(nodeId.get()).get();
prefixBytes = Optional.ofNullable(Bytes.of(type.getNodeTypePrefix()));
}
while (colScannerIter.hasNext() && !batchLimitMet) {
ColumnScanner colScanner = colScannerIter.next();
row = colScanner.getRow();
//extract the nodeId from the returned row if a nodeId was passed
//into the SpanBatchInformation. This is to ensure that the returned
//row nodeId is equal to the nodeId passed in to the span batch information
Optional<String> rowNodeId = Optional.empty();
if (prefixBytes.isPresent()) {
rowNodeId = Optional.of(BindingSetRow.makeFromShardedRow(prefixBytes.get(), row).getNodeId());
}
//if nodeId is present, then results returned by span are filtered
//on the nodeId. This occurs when the hash is not included in the span
if (!rowNodeId.isPresent() || rowNodeId.equals(nodeId)) {
Iterator<ColumnValue> iter = colScanner.iterator();
while (iter.hasNext()) {
if (count >= batchSize) {
batchLimitMet = true;
break;
}
ColumnValue colVal = iter.next();
tx.delete(row, colVal.getColumn());
count++;
}
}
}
if (batchLimitMet) {
return Optional.of(new RowColumn(row));
} else {
return Optional.empty();
}
} catch (Exception e) {
return Optional.empty();
}
}
private void setColumnStatistics(HiveIdentity identity, String objectName, List<ColumnStatisticsObj> statistics, Call1<List<ColumnStatisticsObj>> saveColumnStatistics)
throws TException
{
boolean containsDateStatistics = statistics.stream().anyMatch(stats -> stats.getStatsData().isSetDateStats());
Optional<Boolean> metastoreSupportsDateStatistics = this.metastoreSupportsDateStatistics.get();
if (containsDateStatistics && metastoreSupportsDateStatistics.equals(Optional.of(FALSE))) {
log.debug("Skipping date statistics for %s because metastore does not support them", objectName);
statistics = statistics.stream()
.filter(stats -> !stats.getStatsData().isSetDateStats())
.collect(toImmutableList());
containsDateStatistics = false;
}
if (!containsDateStatistics || metastoreSupportsDateStatistics.equals(Optional.of(TRUE))) {
try (ThriftMetastoreClient client = createMetastoreClient(identity)) {
saveColumnStatistics.call(client, statistics);
}
return;
}
List<ColumnStatisticsObj> statisticsExceptDate = statistics.stream()
.filter(stats -> !stats.getStatsData().isSetDateStats())
.collect(toImmutableList());
List<ColumnStatisticsObj> dateStatistics = statistics.stream()
.filter(stats -> stats.getStatsData().isSetDateStats())
.collect(toImmutableList());
verify(!dateStatistics.isEmpty() && metastoreSupportsDateStatistics.equals(Optional.empty()));
try (ThriftMetastoreClient client = createMetastoreClient(identity)) {
saveColumnStatistics.call(client, statisticsExceptDate);
try {
saveColumnStatistics.call(client, dateStatistics);
}
catch (TException e) {
// When `dateStatistics.size() > 1` we expect something like "TApplicationException: Required field 'colName' is unset! Struct:ColumnStatisticsObj(colName:null, colType:null, statsData:null)"
// When `dateStatistics.size() == 1` we expect something like "TTransportException: java.net.SocketTimeoutException: Read timed out"
log.warn(e, "Failed to save date statistics for %s. Metastore might not support date statistics", objectName);
if (!statisticsExceptDate.isEmpty() && metastoreSetDateStatisticsFailures.incrementAndGet() >= MAX_SET_DATE_STATISTICS_ATTEMPTS) {
this.metastoreSupportsDateStatistics.set(Optional.of(FALSE));
}
return;
}
}
this.metastoreSupportsDateStatistics.set(Optional.of(TRUE));
}
private JoinResult queryJoin(MatchPlayer joining, JoinRequest request, boolean queued) {
final Optional<Team> lastTeam = lastTeam(joining.getPlayerId());
final Optional<Team> chosenTeam = getInstanceOf(request.competitor(), Team.class);
if(request.method() == JoinMethod.REMOTE) {
// If remote joining, force the player onto a team
return JoinAllowed.force(queryAutoJoin(joining, true));
} else if(!request.competitor().isPresent()) {
// If autojoining, and the player is already on a team, the request is satisfied
if(Optionals.isInstance(joining.partyMaybe(), Competitor.class)) {
return JoinDenied.error("command.gameplay.join.alreadyOnTeam", joining.getParty().getComponentName());
}
// If team choosing is disabled, and the match has not started yet, defer the join.
// Note that this can only happen with autojoin. Choosing a team always fails if
// the condition below is true.
if(!queued && !config.allowChoose() && !getMatch().hasStarted()) {
return new JoinQueued();
}
if(lastTeam.isPresent()) {
// If the player was previously on a team, try to join that team first
final JoinResult rejoin = lastTeam.get().queryJoin(joining, true, true);
if(rejoin.isAllowed() || !canSwitchTeams(joining)) return rejoin;
// If the join fails, and the player is allowed to switch teams, fall through to the auto-join
}
// Try to find a team for the player to join
final JoinResult auto = queryAutoJoin(joining, true);
if(auto.isAllowed()) return auto;
if(jmm.canJoinFull(joining) || !joinConfiguration.overfill()) {
return JoinDenied.unavailable("autoJoin.teamsFull");
} else {
// If the player is not premium, and overfill is enabled, plug the shop
return JoinDenied.unavailable("autoJoin.teamsFull")
.also(Links.shopPlug("shop.plug.joinFull"));
}
} else if(chosenTeam.isPresent()) {
// If the player is already on the chosen team, there is nothing to do
if(joining.hasParty() && contains(chosenTeam, joining.getParty())) {
return JoinDenied.error("command.gameplay.join.alreadyOnTeam", joining.getParty().getComponentName());
}
// If team switching is disabled and the player is choosing to re-join their
// last team, don't consider it a "choice" since that's the only team they can
// join anyway. In any other case, check that they are allowed to choose their team.
if(config.allowSwitch() || !chosenTeam.equals(lastTeam)) {
// Team choosing is disabled
if(!config.allowChoose()) {
return JoinDenied.error("command.gameplay.join.choiceDisabled");
}
// Player is not allowed to choose their team
if(!canChooseTeam(joining)) {
return JoinDenied.unavailable("command.gameplay.join.choiceDenied")
.also(Links.shopPlug("shop.plug.chooseTeam"));
}
}
// If team switching is disabled, check if the player is rejoining their former team
if(!canSwitchTeams(joining) && lastTeam.isPresent()) {
if(chosenTeam.equals(lastTeam)) {
return chosenTeam.get().queryJoin(joining, true, true);
} else {
return JoinDenied.error("command.gameplay.join.switchDisabled", lastTeam.get().getComponentName());
}
}
return chosenTeam.get().queryJoin(joining, true, false);
}
return null;
}
private boolean isAntiCsrfTokenValid(final HttpServletRequest request, final Optional<String> token) {
Optional<String> cookie = getAntiCsrfTokenCookie(request);
return token.isPresent() && token.equals(cookie);
}
/**
* Returns the premium price for the specified label and registry, or absent if the label is not
* premium.
*/
public static Optional<Money> getPremiumPrice(String label, Registry registry) {
// If the registry has no configured premium list, then no labels are premium.
if (registry.getPremiumList() == null) {
return Optional.empty();
}
DateTime startTime = DateTime.now(UTC);
String listName = registry.getPremiumList().getName();
Optional<PremiumList> optionalPremiumList = PremiumList.getCached(listName);
checkState(optionalPremiumList.isPresent(), "Could not load premium list '%s'", listName);
PremiumList premiumList = optionalPremiumList.get();
PremiumListRevision revision;
try {
revision = cachePremiumListRevisions.get(premiumList.getRevisionKey());
} catch (InvalidCacheLoadException | ExecutionException e) {
throw new RuntimeException(
"Could not load premium list revision " + premiumList.getRevisionKey(), e);
}
checkState(
revision.getProbablePremiumLabels() != null,
"Probable premium labels Bloom filter is null on revision '%s'",
premiumList.getRevisionKey());
CheckResults checkResults = checkStatus(revision, label);
DomainLabelMetrics.recordPremiumListCheckOutcome(
registry.getTldStr(),
listName,
checkResults.checkOutcome(),
DateTime.now(UTC).getMillis() - startTime.getMillis());
// Also load the value from Cloud SQL, compare the two results, and log if different.
try {
Optional<Money> priceFromSql = PremiumListDao.getPremiumPrice(label, registry);
if (!priceFromSql.equals(checkResults.premiumPrice())) {
logger.atWarning().log(
"Unequal prices for domain %s.%s from Datastore (%s) and Cloud SQL (%s).",
label, registry.getTldStr(), checkResults.premiumPrice(), priceFromSql);
}
} catch (Throwable t) {
logger.atSevere().withCause(t).log(
"Error loading price of domain %s.%s from Cloud SQL.", label, registry.getTldStr());
}
return checkResults.premiumPrice();
}
@Override
public boolean concerns(Environment environment, Optional<RegionName> region) {
if (environment != this.environment) return false;
if (region.isPresent() && ! region.equals(this.region)) return false;
return true;
}
/**
* Checks whether two values for a single dimension are compatible.
*
* <p>This happens if they have the same value or any of them is absent.
*/
private static boolean areCompatible(Optional<String> value1, Optional<String> value2) {
return value1.equals(value2) || !value1.isPresent() || !value2.isPresent();
}