Java Code Examples for com.google.common.base.Optional.fromNullable()

The following are Jave code examples for showing how to use fromNullable() of the com.google.common.base.Optional class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: elastic-job-cloud   File: StatisticRdbRepository.java   View Source Code Vote up 6 votes
/**
 * 获取最近一条任务运行结果统计数据.
 * 
 * @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);
}
 
Example 2
Project: redirector   File: FlavorRuleToTestConverter.java   View Source Code Vote up 6 votes
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;
}
 
Example 3
Project: verify-hub   File: PolicyExceptionMapper.java   View Source Code Vote up 6 votes
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));
    }
}
 
Example 4
Project: cakes   File: OptionalDemo.java   View Source Code Vote up 5 votes
/**
 * 创建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);
}
 
Example 5
Project: dremio-oss   File: MaterializationTestStoragePlugin.java   View Source Code Vote up 5 votes
@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());
}
 
Example 6
Project: n4js   File: N4JSRuntimeCore.java   View Source Code Vote up 5 votes
@Override
public Optional<? extends IN4JSProject> findProject(URI nestedLocation) {
	if (nestedLocation == null) {
		return Optional.absent();
	}
	IN4JSProject result = model.findProjectWith(nestedLocation);
	return Optional.fromNullable(result);
}
 
Example 7
Project: n4js   File: N4JSProject.java   View Source Code Vote up 5 votes
@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());
}
 
Example 8
Project: hashsdn-controller   File: RpcRoutingStrategy.java   View Source Code Vote up 5 votes
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();
}
 
Example 9
Project: verify-hub   File: InboundResponseFromIdpDtoBuilder.java   View Source Code Vote up 5 votes
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);
}
 
Example 10
Project: verify-matching-service-adapter   File: AddressBuilder.java   View Source Code Vote up 4 votes
public AddressBuilder withInternationalPostCode(final String internationalPostCode) {
    this.internationalPostCode = Optional.fromNullable(internationalPostCode);
    return this;
}
 
Example 11
Project: Elasticsearch   File: ClusteredBy.java   View Source Code Vote up 4 votes
public ClusteredBy(@Nullable Expression column, @Nullable Expression numberOfShards) {
    this.column = Optional.fromNullable(column);
    this.numberOfShards = Optional.fromNullable(numberOfShards);
}
 
Example 12
Project: jPUBG   File: MatchValidationService.java   View Source Code Vote up 4 votes
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);
}
 
Example 13
Project: Elasticsearch   File: CurrentTime.java   View Source Code Vote up 4 votes
public CurrentTime(Type type, @Nullable Integer precision)
{
    checkNotNull(type, "type is null");
    this.type = type;
    this.precision = Optional.fromNullable(precision);
}
 
Example 14
Project: verify-hub   File: FraudFromIdpBuilder.java   View Source Code Vote up 4 votes
public FraudFromIdpBuilder withPrincipalIpAddressSeenByIdp(String principalIpAddressAsSeenByIdp) {
    this.principalIpAddressAsSeenByIdp = Optional.fromNullable(principalIpAddressAsSeenByIdp);
    return this;
}
 
Example 15
Project: hashsdn-controller   File: AbstractLeader.java   View Source Code Vote up 4 votes
/**
 *  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());
    }
}
 
Example 16
Project: SECP   File: PermissionDAO.java   View Source Code Vote up 4 votes
public Optional<Permission> find(long id) {
    return Optional.fromNullable(get(id));
}
 
Example 17
Project: hashsdn-controller   File: AbstractWriteTransaction.java   View Source Code Vote up 4 votes
/**
 * @deprecated Use {@link YangInstanceIdentifier#getParent()} instead.
 */
@Deprecated
protected static Optional<YangInstanceIdentifier> getParent(final YangInstanceIdentifier child) {
    return Optional.fromNullable(child.getParent());
}
 
Example 18
Project: verify-hub   File: EventSinkHubEventLoggerTest.java   View Source Code Vote up 4 votes
@Test
public void logIdpAuthnSucceededEvent_shouldContainLevelsOfAssuranceInDetailsFieldForBilling() throws Exception {

    String requestId = "requestId";
    DateTimeFreezer.freezeTime();
    int sessionDuration = 10;
    DateTime sessionExpiryTime = DateTime.now().plusMinutes(sessionDuration);
    SessionId sessionId = aSessionId().build();
    String idpEntityId = "idp entity id";
    String transactionEntityId = "transaction entity id";
    LevelOfAssurance minimumLevelOfAssurance = LevelOfAssurance.LEVEL_1;
    LevelOfAssurance requiredLevelOfAssurance = LevelOfAssurance.LEVEL_2;
    LevelOfAssurance providedLevelOfAssurance = LevelOfAssurance.LEVEL_2;
    PersistentId persistentId = aPersistentId().withNameId("nameId").build();
    Optional<String> principalIpAddress = Optional.fromNullable("principal ip address");
    String principalIpAddressAsSeenByHub = "principal-ip-address-seen-by-hub";

    EventSinkHubEventLogger eventLogger = new EventSinkHubEventLogger(serviceInfo, eventSinkProxy);

    ArgumentCaptor<EventSinkHubEvent> eventCaptor = ArgumentCaptor.forClass(EventSinkHubEvent.class);

    //When
    eventLogger.logIdpAuthnSucceededEvent(sessionId, sessionExpiryTime, idpEntityId, transactionEntityId, persistentId, requestId, minimumLevelOfAssurance, requiredLevelOfAssurance, providedLevelOfAssurance, principalIpAddress, principalIpAddressAsSeenByHub);

    //Then
    verify(eventSinkProxy).logHubEvent(eventCaptor.capture());

    EventSinkHubEvent actualEvent = eventCaptor.getValue();

    assertThat(actualEvent.getTimestamp()).isEqualTo(DateTime.now());
    assertThat(actualEvent.getSessionId()).isEqualTo(sessionId.getSessionId());
    assertThat(actualEvent.getEventType()).isEqualTo(EventSinkHubEventConstants.EventTypes.SESSION_EVENT);

    Map<EventDetailsKey, String> details = actualEvent.getDetails();

    assertThat(details.containsKey(minimum_level_of_assurance)).isTrue();
    String actualMinimumLevelOfAssurance = details.get(minimum_level_of_assurance);
    assertThat(actualMinimumLevelOfAssurance).isEqualTo(minimumLevelOfAssurance.name());

    assertThat(details.containsKey(required_level_of_assurance)).isTrue();
    String actualRequiredLevelOfAssurance = details.get(required_level_of_assurance);
    assertThat(actualRequiredLevelOfAssurance).isEqualTo(requiredLevelOfAssurance.name());

    assertThat(details.containsKey(provided_level_of_assurance)).isTrue();
    String actualProvidedLevelOfAssurance = details.get(provided_level_of_assurance);
    assertThat(actualProvidedLevelOfAssurance).isEqualTo(providedLevelOfAssurance.name());

    assertThat(details.containsKey(principal_ip_address_as_seen_by_idp)).isTrue();
    String actualPrincipalIpAddress = details.get(principal_ip_address_as_seen_by_idp);
    assertThat(actualPrincipalIpAddress).isEqualTo(principalIpAddress.get());

    assertThat(details.containsKey(principal_ip_address_as_seen_by_hub)).isTrue();
    assertThat(details.get(principal_ip_address_as_seen_by_hub)).isEqualTo(principalIpAddressAsSeenByHub);

    assertThat(details.containsKey(request_id)).isTrue();
    assertThat(details.get(request_id)).isEqualTo(requestId);
}
 
Example 19
Project: JAMCore   File: GameStatistics.java   View Source Code Vote up 2 votes
public static void setGameStatisticDisplayer(GameStatisticDisplayer	gameStatisticDisplayerImplementation) {
			
	GameStatisticDisplayerImplementation= Optional.fromNullable(gameStatisticDisplayerImplementation);
		
}
 
Example 20
Project: elastic-job-cloud   File: CloudAppConfigurationService.java   View Source Code Vote up 2 votes
/**
 * 根据云作业App名称获取App配置.
 *
 * @param appName 云作业App名称
 * @return 云作业App配置
 */
public Optional<CloudAppConfiguration> load(final String appName) {
    return Optional.fromNullable(CloudAppConfigurationGsonFactory.fromJson(regCenter.get(CloudAppConfigurationNode.getRootNodePath(appName))));
}