當前位置: 首頁>>代碼示例>>Java>>正文


Java Optional.fromNullable方法代碼示例

本文整理匯總了Java中com.google.common.base.Optional.fromNullable方法的典型用法代碼示例。如果您正苦於以下問題:Java Optional.fromNullable方法的具體用法?Java Optional.fromNullable怎麽用?Java Optional.fromNullable使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.google.common.base.Optional的用法示例。


在下文中一共展示了Optional.fromNullable方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: findLatestTaskResultStatistics

import com.google.common.base.Optional; //導入方法依賴的package包/類
/**
 * 獲取最近一條任務運行結果統計數據.
 * 
 * @param statisticInterval 統計時間間隔
 * @return 任務運行結果統計數據對象
 */
public Optional<TaskResultStatistics> findLatestTaskResultStatistics(final StatisticInterval statisticInterval) {
    TaskResultStatistics result = null;
    String sql = String.format("SELECT id, success_count, failed_count, statistics_time, creation_time FROM %s order by id DESC LIMIT 1", 
            TABLE_TASK_RESULT_STATISTICS + "_" + statisticInterval);
    try (
            Connection conn = dataSource.getConnection();
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery()
            ) {
        while (resultSet.next()) {
            result = new TaskResultStatistics(resultSet.getLong(1), resultSet.getInt(2), resultSet.getInt(3), 
                    statisticInterval, new Date(resultSet.getTimestamp(4).getTime()), new Date(resultSet.getTimestamp(5).getTime()));
        }
    } catch (final SQLException ex) {
        // TODO 記錄失敗直接輸出日誌,未來可考慮配置化
        log.error("Fetch latest taskResultStatistics from DB error:", ex);
    }
    return Optional.fromNullable(result);
}
 
開發者ID:elasticjob,項目名稱:elastic-job-cloud,代碼行數:26,代碼來源:StatisticRdbRepository.java

示例2: obtainExpectedResponse

import com.google.common.base.Optional; //導入方法依賴的package包/類
private TestSuiteResponse obtainExpectedResponse(IfExpression rule) {
    TestSuiteResponse response = new TestSuiteResponse();

    for (Expressions expressions : RulesUtils.getReturn(rule)) {
        if (expressions instanceof Server) {
            Optional<String> path = Optional.fromNullable(((Server) expressions).getPath());
            if (path.or("").contains("/")) {
                XreStackPath stackPath = new XreStackPath(path.get() + "/" + serviceName);
                response.setFlavor(stackPath.getFlavor());
                response.setXreStack(stackPath.getStackOnlyPath());
            } else {
                response.setFlavor(path.or(""));
            }
            response.setRule(rule.getId());

            return response;
        } else {
            log.warn("Rule {} is skipped. ServerGroup is not supported", rule.getId());
        }
    }

    return null;
}
 
開發者ID:Comcast,項目名稱:redirector,代碼行數:24,代碼來源:FlavorRuleToTestConverter.java

示例3: getSessionId

import com.google.common.base.Optional; //導入方法依賴的package包/類
protected Optional<SessionId> getSessionId() {
    // Are there any uris in Policy that contain the session id as a query string rather than as part of the path or is this just here coz it was copied from shared-rest   ?
    String parameter = httpServletRequest.getParameter(Urls.SharedUrls.SESSION_ID_PARAM);
    if (Strings.isNullOrEmpty(parameter)) {
        parameter = httpServletRequest.getParameter(Urls.SharedUrls.RELAY_STATE_PARAM);
    }
    if (Strings.isNullOrEmpty(parameter)) {
        MultivaluedMap<String, String> pathParameters = uriInfo.getPathParameters();
        parameter = pathParameters.getFirst(Urls.SharedUrls.SESSION_ID_PARAM);
    }
    if (Strings.isNullOrEmpty(parameter)) {
        return Optional.absent();
    } else {
        return Optional.fromNullable(new SessionId(parameter));
    }
}
 
開發者ID:alphagov,項目名稱:verify-hub,代碼行數:17,代碼來源:PolicyExceptionMapper.java

示例4: testFromNullable

import com.google.common.base.Optional; //導入方法依賴的package包/類
/**
 * 創建Optional: fromNullable(T)
 */
@Test
public void testFromNullable() {
    String str = "";
    Optional<String> op1 = Optional.fromNullable(str);

    str = null;

    // 此時即使str為null,也不會拋異常
    Optional<String> op2 = Optional.fromNullable(str);
}
 
開發者ID:cbooy,項目名稱:cakes,代碼行數:14,代碼來源:OptionalDemo.java

示例5: getView

import com.google.common.base.Optional; //導入方法依賴的package包/類
@Override
public ViewTable getView(final List<String> path, final SchemaConfig schemaConfig) {
  if (path.size() != 2) {
    logger.debug("path must consists of 2 segments [pluginName, layoutId]. got {}",
        MoreObjects.toStringHelper(this).add("path", path));
    return null;
  }

  final String layoutId = path.get(1);
  final Optional<RelNode> layout = Optional.fromNullable(plans.getIfPresent(layoutId));
  if (!layout.isPresent()) {
    return null;
  }
  return new MaterializedTestViewTable(layout.get(), schemaConfig.getUserName(), schemaConfig.getViewExpansionContext());
}
 
開發者ID:dremio,項目名稱:dremio-oss,代碼行數:16,代碼來源:MaterializationTestStoragePlugin.java

示例6: findProject

import com.google.common.base.Optional; //導入方法依賴的package包/類
@Override
public Optional<? extends IN4JSProject> findProject(URI nestedLocation) {
	if (nestedLocation == null) {
		return Optional.absent();
	}
	IN4JSProject result = model.findProjectWith(nestedLocation);
	return Optional.fromNullable(result);
}
 
開發者ID:eclipse,項目名稱:n4js,代碼行數:9,代碼來源:N4JSRuntimeCore.java

示例7: getImplementationId

import com.google.common.base.Optional; //導入方法依賴的package包/類
@Override
public Optional<String> getImplementationId() {
	if (!exists()) {
		return Optional.absent();
	}
	final ProjectDescription pd = model.getProjectDescription(getLocation());
	if (pd == null) {
		return Optional.absent();
	}
	return Optional.fromNullable(pd.getImplementationId());
}
 
開發者ID:eclipse,項目名稱:n4js,代碼行數:12,代碼來源:N4JSProject.java

示例8: getRoutingContext

import com.google.common.base.Optional; //導入方法依賴的package包/類
public static Optional<QName> getRoutingContext(final DataSchemaNode schemaNode) {
    for (UnknownSchemaNode extension : schemaNode.getUnknownSchemaNodes()) {
        if (CONTEXT_REFERENCE.equals(extension.getNodeType())) {
            return Optional.fromNullable(extension.getQName());
        }
    }
    return Optional.absent();
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:9,代碼來源:RpcRoutingStrategy.java

示例9: buildDTO

import com.google.common.base.Optional; //導入方法依賴的package包/類
private static InboundResponseFromIdpDto buildDTO(IdpIdaStatus.Status status, String idpEntityId,
                                                  Optional<LevelOfAssurance> levelOfAssurance,
                                                  Optional<String> fraudText) {
    return new InboundResponseFromIdpDto(
            status,
            Optional.fromNullable("message"),
            idpEntityId,
            Optional.fromNullable("authnStatement"),
            Optional.of("encrypted-mds-assertion"),
            Optional.fromNullable("pid"),
            Optional.fromNullable("principalipseenbyidp"),
            levelOfAssurance,
            fraudText,
            fraudText);
}
 
開發者ID:alphagov,項目名稱:verify-hub,代碼行數:16,代碼來源:InboundResponseFromIdpDtoBuilder.java

示例10: withInternationalPostCode

import com.google.common.base.Optional; //導入方法依賴的package包/類
public AddressBuilder withInternationalPostCode(final String internationalPostCode) {
    this.internationalPostCode = Optional.fromNullable(internationalPostCode);
    return this;
}
 
開發者ID:alphagov,項目名稱:verify-matching-service-adapter,代碼行數:5,代碼來源:AddressBuilder.java

示例11: ClusteredBy

import com.google.common.base.Optional; //導入方法依賴的package包/類
public ClusteredBy(@Nullable Expression column, @Nullable Expression numberOfShards) {
    this.column = Optional.fromNullable(column);
    this.numberOfShards = Optional.fromNullable(numberOfShards);
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:5,代碼來源:ClusteredBy.java

示例12: validateSingleMatch

import com.google.common.base.Optional; //導入方法依賴的package包/類
public void validateSingleMatch(final Match match) {
    Optional<Match> matchOptional = Optional.fromNullable(match);
    Preconditions.checkState(matchOptional.isPresent(), Messages.CANNOT_GET_MATCH_FROM_SEASON_MATCH_IS_NULL);
}
 
開發者ID:Lukaszpg,項目名稱:jPUBG,代碼行數:5,代碼來源:MatchValidationService.java

示例13: CurrentTime

import com.google.common.base.Optional; //導入方法依賴的package包/類
public CurrentTime(Type type, @Nullable Integer precision)
{
    checkNotNull(type, "type is null");
    this.type = type;
    this.precision = Optional.fromNullable(precision);
}
 
開發者ID:baidu,項目名稱:Elasticsearch,代碼行數:7,代碼來源:CurrentTime.java

示例14: withPrincipalIpAddressSeenByIdp

import com.google.common.base.Optional; //導入方法依賴的package包/類
public FraudFromIdpBuilder withPrincipalIpAddressSeenByIdp(String principalIpAddressAsSeenByIdp) {
    this.principalIpAddressAsSeenByIdp = Optional.fromNullable(principalIpAddressAsSeenByIdp);
    return this;
}
 
開發者ID:alphagov,項目名稱:verify-hub,代碼行數:5,代碼來源:FraudFromIdpBuilder.java

示例15: sendSnapshotChunk

import com.google.common.base.Optional; //導入方法依賴的package包/類
/**
 *  Sends a snapshot chunk to a given follower
 *  InstallSnapshot should qualify as a heartbeat too.
 */
private void sendSnapshotChunk(final ActorSelection followerActor, final FollowerLogInformation followerLogInfo) {
    if (snapshotHolder.isPresent()) {
        LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
        if (installSnapshotState == null) {
            installSnapshotState = new LeaderInstallSnapshotState(context.getConfigParams().getSnapshotChunkSize(),
                    logName());
            followerLogInfo.setLeaderInstallSnapshotState(installSnapshotState);
        }

        try {
            // Ensure the snapshot bytes are set - this is a no-op.
            installSnapshotState.setSnapshotBytes(snapshotHolder.get().getSnapshotBytes());

            if (!installSnapshotState.canSendNextChunk()) {
                return;
            }

            byte[] nextSnapshotChunk = installSnapshotState.getNextChunk();

            log.debug("{}: next snapshot chunk size for follower {}: {}", logName(), followerLogInfo.getId(),
                    nextSnapshotChunk.length);

            int nextChunkIndex = installSnapshotState.incrementChunkIndex();
            Optional<ServerConfigurationPayload> serverConfig = Optional.absent();
            if (installSnapshotState.isLastChunk(nextChunkIndex)) {
                serverConfig = Optional.fromNullable(context.getPeerServerInfo(true));
            }

            followerActor.tell(
                new InstallSnapshot(currentTerm(), context.getId(),
                    snapshotHolder.get().getLastIncludedIndex(),
                    snapshotHolder.get().getLastIncludedTerm(),
                    nextSnapshotChunk,
                    nextChunkIndex,
                    installSnapshotState.getTotalChunks(),
                    Optional.of(installSnapshotState.getLastChunkHashCode()),
                    serverConfig
                ).toSerializable(followerLogInfo.getRaftVersion()),
                actor()
            );

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        log.debug("{}: InstallSnapshot sent to follower {}, Chunk: {}/{}", logName(), followerActor.path(),
            installSnapshotState.getChunkIndex(), installSnapshotState.getTotalChunks());
    }
}
 
開發者ID:hashsdn,項目名稱:hashsdn-controller,代碼行數:54,代碼來源:AbstractLeader.java


注:本文中的com.google.common.base.Optional.fromNullable方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。