Java Code Examples for java.time.Instant.ofEpochMilli()

The following are Jave code examples for showing how to use ofEpochMilli() of the java.time.Instant class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: rskj   File: RetiringFederationTest.java   Source Code and License Vote up 6 votes
private BridgeStorageProviderInitializer buildInitializer(boolean present) {
    final int minFederators = 10;
    final int maxFederators = 16;

    return (BridgeStorageProvider provider, Repository repository, int executionIndex) -> {
        if (present) {
            int numFederators = Helper.randomInRange(minFederators, maxFederators);
            List<BtcECKey> federatorKeys = new ArrayList<>();
            for (int i = 0; i < numFederators; i++) {
                federatorKeys.add(new BtcECKey());
            }
            retiringFederation = new Federation(
                    federatorKeys,
                    Instant.ofEpochMilli(new Random().nextLong()),
                    Helper.randomInRange(1, 10),
                    networkParameters
            );
            provider.setNewFederation(bridgeConstants.getGenesisFederation());
            provider.setOldFederation(retiringFederation);
        } else {
            retiringFederation = null;
        }
    };
}
 
Example 2
Project: pyplyn   File: FormatUtils.java   Source Code and License Vote up 6 votes
/**
 * Parses string as time
 *   accepted formats are milliseconds from epoch and valid date string
 *
 * @throws DateTimeParseException if the value cannot be parsed as valid datetime
 */
public static ZonedDateTime parseUTCTime(String value) {
    try {
        // parses ms unix time and returns at UTC offset
        Instant instant = Instant.ofEpochMilli(Long.parseLong(value));
        return instant.atZone(ZoneOffset.UTC);

    } catch (NumberFormatException e) {
        // parse passed date
        return Optional.of(ZonedDateTime.parse(value))
                // convert to UTC
                .map(zdt -> zdt.withZoneSameInstant(ZoneOffset.UTC))
                // and return the value; this is safe to call without orElse,
                //   since ZonedDateTime will throw an exception if it cannot parse the value
                .get();
    }
}
 
Example 3
Project: cakes   File: InstantDemo.java   Source Code and License Vote up 6 votes
/**
 * 初始化
 */
@Test
public void testCreate() {
    // 此时获取的是 UTC时区的时间,北京时间需要加上偏移量
    Instant instant = Instant.now();
    System.out.println(instant);

    // 偏移8个小时,东八区
    OffsetDateTime dateTime = instant.atOffset(ZoneOffset.ofHours(8));
    System.out.println(dateTime);

    // 相对1970-1-1 00:00:00,向后偏移1000000毫秒
    Instant instantMilli = Instant.ofEpochMilli(1000000);
    System.out.println(instantMilli);

    // 相对1970-1-1 00:00:00,向后偏移60秒
    Instant instantSecond = Instant.ofEpochSecond(60);
    System.out.println(instantSecond);

}
 
Example 4
Project: rskj   File: BridgeSerializationUtils.java   Source Code and License Vote up 6 votes
public static Federation deserializeFederation(byte[] data, Context btcContext) {
    RLPList rlpList = (RLPList)RLP.decode2(data).get(0);

    if (rlpList.size() != FEDERATION_RLP_LIST_SIZE) {
        throw new RuntimeException(String.format("Invalid serialized Federation. Expected %d elements but got %d", FEDERATION_RLP_LIST_SIZE, rlpList.size()));
    }

    byte[] creationTimeBytes = rlpList.get(FEDERATION_CREATION_TIME_INDEX).getRLPData();
    Instant creationTime = Instant.ofEpochMilli(BigIntegers.fromUnsignedByteArray(creationTimeBytes).longValue());

    List<BtcECKey> pubKeys = ((RLPList) rlpList.get(FEDERATION_PUB_KEYS_INDEX)).stream()
            .map(pubKeyBytes -> BtcECKey.fromPublicOnly(pubKeyBytes.getRLPData()))
            .collect(Collectors.toList());

    byte[] creationBlockNumberBytes = rlpList.get(FEDERATION_CREATION_BLOCK_NUMBER_INDEX).getRLPData();
    long creationBlockNumber = BigIntegers.fromUnsignedByteArray(creationBlockNumberBytes).longValue();

    return new Federation(pubKeys, creationTime, creationBlockNumber, btcContext.getParams());
}
 
Example 5
Project: devoxxus-jhipster-microservices-demo   File: CustomAuditEventRepository.java   Source Code and License Vote up 5 votes
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void add(AuditEvent event) {
    if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
        !Constants.ANONYMOUS_USER.equals(event.getPrincipal())) {

        PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
        persistentAuditEvent.setPrincipal(event.getPrincipal());
        persistentAuditEvent.setAuditEventType(event.getType());
        Instant instant = Instant.ofEpochMilli(event.getTimestamp().getTime());
        persistentAuditEvent.setAuditEventDate(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
        persistentAuditEvent.setData(auditEventConverter.convertDataToStrings(event.getData()));
        persistenceAuditEventRepository.save(persistentAuditEvent);
    }
}
 
Example 6
Project: Armory   File: ActivityService.java   Source Code and License Vote up 5 votes
@SubscribeMapping("/topic/activity")
@SendTo("/topic/tracker")
public ActivityDTO sendActivity(@Payload ActivityDTO activityDTO, StompHeaderAccessor stompHeaderAccessor, Principal principal) {
    activityDTO.setUserLogin(SecurityUtils.getCurrentUserLogin());
    activityDTO.setUserLogin(principal.getName());
    activityDTO.setSessionId(stompHeaderAccessor.getSessionId());
    activityDTO.setIpAddress(stompHeaderAccessor.getSessionAttributes().get(IP_ADDRESS).toString());
    Instant instant = Instant.ofEpochMilli(Calendar.getInstance().getTimeInMillis());
    activityDTO.setTime(dateTimeFormatter.format(ZonedDateTime.ofInstant(instant, ZoneOffset.systemDefault())));
    log.debug("Sending user tracking data {}", activityDTO);
    return activityDTO;
}
 
Example 7
Project: Supreme-Bot   File: Util.java   Source Code and License Vote up 5 votes
public static final Instant stringToInstant(String text) {
    try {
        return Instant.parse(text);
    } catch (Exception ex) {
        try {
            return Instant.ofEpochMilli(Long.parseLong(text));
        } catch (Exception ex2) {
            try {
                return Timestamp.valueOf(text).toInstant();
            } catch (Exception ex3) {
                return null;
            }
        }
    }
}
 
Example 8
Project: verify-matching-service-adapter   File: JodaAndJavaDateTimeConverters.java   Source Code and License Vote up 5 votes
public static final Instant jodaDateTimeToJavaInstant(@NotNull DateTime dateTime) {
    if (dateTime == null) {
        return null;
    }

    return Instant.ofEpochMilli(dateTime.toInstant().getMillis());
}
 
Example 9
Project: matrix-java-sdk   File: MatrixJsonEvent.java   Source Code and License Vote up 5 votes
public MatrixJsonEvent(JsonObject obj) {
    super(obj);

    id = getString("event_id");
    type = getString("type");
    time = Instant.ofEpochMilli(obj.get("origin_server_ts").getAsLong());
    age = getInt("age", -1);
    sender = MatrixID.from(getString("sender")).acceptable();
}
 
Example 10
Project: simple-openid-provider   File: AuthorizationEndpoint.java   Source Code and License Vote up 5 votes
private AuthenticationSuccessResponse handleHybridFlow(AuthenticationRequest authRequest,
		OIDCClientInformation client, HttpServletRequest request, Subject subject) throws GeneralException {
	ResponseType responseType = authRequest.getResponseType();
	ResponseMode responseMode = authRequest.impliedResponseMode();
	ClientID clientId = authRequest.getClientID();
	URI redirectUri = authRequest.getRedirectionURI();
	Scope requestedScope = authRequest.getScope();
	State state = authRequest.getState();
	CodeChallenge codeChallenge = authRequest.getCodeChallenge();
	CodeChallengeMethod codeChallengeMethod = authRequest.getCodeChallengeMethod();
	Nonce nonce = authRequest.getNonce();

	Instant authenticationTime = Instant.ofEpochMilli(request.getSession().getCreationTime());
	ACR acr = this.acr;
	AMR amr = AMR.PWD;
	SessionID sessionId = new SessionID(request.getSession().getId());
	State sessionState = this.sessionManagementEnabled ? State.parse(sessionId.getValue()) : null;

	Scope scope = this.scopeResolver.resolve(subject, requestedScope, client.getOIDCMetadata());
	AuthorizationCodeContext context = new AuthorizationCodeContext(subject, clientId, redirectUri, scope,
			authenticationTime, acr, amr, sessionId, codeChallenge, codeChallengeMethod, nonce);
	AuthorizationCode code = this.authorizationCodeService.create(context);
	AccessToken accessToken = null;

	if (responseType.contains(ResponseType.Value.TOKEN)) {
		AccessTokenRequest accessTokenRequest = new AccessTokenRequest(subject, client, scope);
		accessToken = this.tokenService.createAccessToken(accessTokenRequest);
	}

	JWT idToken = null;

	if (responseType.contains(OIDCResponseTypeValue.ID_TOKEN)) {
		IdTokenRequest idTokenRequest = new IdTokenRequest(subject, client, scope, authenticationTime, acr, amr,
				sessionId, nonce, accessToken, code);
		idToken = this.tokenService.createIdToken(idTokenRequest);
	}

	return new AuthenticationSuccessResponse(redirectUri, code, idToken, accessToken, state, sessionState,
			responseMode);
}
 
Example 11
Project: rskj   File: BridgeDevNetConstants.java   Source Code and License Vote up 4 votes
BridgeDevNetConstants() {
        btcParamsString = NetworkParameters.ID_TESTNET;

        BtcECKey federator0PublicKey = BtcECKey.fromPublicOnly(Hex.decode("0234ab441aa5edb1c7341315e21408c3947cce345156c465b3336e8c6a5552f35f"));
        BtcECKey federator1PublicKey = BtcECKey.fromPublicOnly(Hex.decode("03301f6c4422aa96d85f52a93612a0c6eeea3d04cfa32f97a7a764c67e062e992a"));
        BtcECKey federator2PublicKey = BtcECKey.fromPublicOnly(Hex.decode("02d33a1f8f5cfa2f7be71b0002710f4c8f3ea44fef40056be7b89ed3ca0eb3431c"));

        List<BtcECKey> genesisFederationPublicKeys = Lists.newArrayList(
                federator0PublicKey, federator1PublicKey, federator2PublicKey
        );
        
        // Currently set to:
        // Monday, November 13, 2017 9:00:00 PM GMT-03:00
        Instant genesisFederationAddressCreatedAt = Instant.ofEpochMilli(1510617600l);

        // Expected federation address is:
        // 2NCEo1RdmGDj6MqiipD6DUSerSxKv79FNWX
        genesisFederation = new Federation(
                genesisFederationPublicKeys,
                genesisFederationAddressCreatedAt,
                1L,
                getBtcParams()
        );

        btc2RskMinimumAcceptableConfirmations = 1;
        btc2RskMinimumAcceptableConfirmationsOnRsk = 10;
        rsk2BtcMinimumAcceptableConfirmations = 10;

        updateBridgeExecutionPeriod = 30000; // 30secs

        maxBtcHeadersPerRskBlock = 500;

        minimumLockTxValue = Coin.valueOf(1000000);
        minimumReleaseTxValue = Coin.valueOf(500000);

        // Keys generated with GenNodeKey using generators 'auth-a' through 'auth-e'
        List<ECKey> federationChangeAuthorizedKeys = Arrays.stream(new String[]{
                "04dde17c5fab31ffc53c91c2390136c325bb8690dc135b0840075dd7b86910d8ab9e88baad0c32f3eea8833446a6bc5ff1cd2efa99ecb17801bcb65fc16fc7d991",
                "04af886c67231476807e2a8eee9193878b9d94e30aa2ee469a9611d20e1e1c1b438e5044148f65e6e61bf03e9d72e597cb9cdea96d6fc044001b22099f9ec403e2",
                "045d4dedf9c69ab3ea139d0f0da0ad00160b7663d01ce7a6155cd44a3567d360112b0480ab6f31cac7345b5f64862205ea7ccf555fcf218f87fa0d801008fecb61",
                "04709f002ac4642b6a87ea0a9dc76eeaa93f71b3185985817ec1827eae34b46b5d869320efb5c5cbe2a5c13f96463fe0210710b53352a4314188daffe07bd54154",
//                "04aff62315e9c18004392a5d9e39496ff5794b2d9f43ab4e8ade64740d7fdfe896969be859b43f26ef5aa4b5a0d11808277b4abfa1a07cc39f2839b89cc2bc6b4c"
                "0447b4aba974c61c6c4045893267346730ec965b308e7ca04a899cf06a901face3106e1eef1bdad04928cd8263522eda4872d20d3fe1ef5e551785c4a482656a6e"
        }).map(hex -> ECKey.fromPublicOnly(Hex.decode(hex))).collect(Collectors.toList());

        federationChangeAuthorizer = new AddressBasedAuthorizer(
                federationChangeAuthorizedKeys,
                AddressBasedAuthorizer.MinimumRequiredCalculation.MAJORITY
        );

        // Key generated with GenNodeKey using generator 'auth-lock-whitelist'
        List<ECKey> lockWhitelistAuthorizedKeys = Arrays.stream(new String[]{
//                "04641fb250d7ca7a1cb4f530588e978013038ec4294d084d248869dd54d98873e45c61d00ceeaeeb9e35eab19fa5fbd8f07cb8a5f0ddba26b4d4b18349c09199ad"
                "0447b4aba974c61c6c4045893267346730ec965b308e7ca04a899cf06a901face3106e1eef1bdad04928cd8263522eda4872d20d3fe1ef5e551785c4a482656a6e"
        }).map(hex -> ECKey.fromPublicOnly(Hex.decode(hex))).collect(Collectors.toList());

        lockWhitelistChangeAuthorizer = new AddressBasedAuthorizer(
                lockWhitelistAuthorizedKeys,
                AddressBasedAuthorizer.MinimumRequiredCalculation.ONE
        );

        federationActivationAge = 10L;

        fundsMigrationAgeSinceActivationBegin = 15L;
        fundsMigrationAgeSinceActivationEnd = 100L;

        // Key generated with GenNodeKey using generator 'auth-fee-per-kb'
        List<ECKey> feePerKbAuthorizedKeys = Arrays.stream(new String[]{
                "0430c7d0146029db553d60cf11e8d39df1c63979ee2e4cd1e4d4289a5d88cfcbf3a09b06b5cbc88b5bfeb4b87a94cefab81c8d44655e7e813fc3e18f51cfe7e8a0"
        }).map(hex -> ECKey.fromPublicOnly(Hex.decode(hex))).collect(Collectors.toList());

        feePerKbChangeAuthorizer = new AddressBasedAuthorizer(
                feePerKbAuthorizedKeys,
                AddressBasedAuthorizer.MinimumRequiredCalculation.MAJORITY
        );

        genesisFeePerKb = Coin.MILLICOIN;
    }
 
Example 12
Project: flux-capacitor-client   File: AxonDomainEventEntry.java   Source Code and License Vote up 4 votes
@Override
public Instant getTimestamp() {
    return Instant.ofEpochMilli(axonMessage.getTimestamp());
}
 
Example 13
Project: rskj   File: BridgeSerializationUtilsTest.java   Source Code and License Vote up 4 votes
@Test
public void serializeFederation() throws Exception {
    PowerMockito.mockStatic(RLP.class);
    mock_RLP_encodeBigInteger();
    mock_RLP_encodeList();
    mock_RLP_encodeElement();

    byte[][] publicKeyBytes = new byte[][]{
            BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKey(),
    };

    Federation federation = new Federation(
        Arrays.asList(new BtcECKey[]{
                BtcECKey.fromPublicOnly(publicKeyBytes[0]),
                BtcECKey.fromPublicOnly(publicKeyBytes[1]),
                BtcECKey.fromPublicOnly(publicKeyBytes[2]),
                BtcECKey.fromPublicOnly(publicKeyBytes[3]),
                BtcECKey.fromPublicOnly(publicKeyBytes[4]),
                BtcECKey.fromPublicOnly(publicKeyBytes[5]),
        }),
        Instant.ofEpochMilli(0xabcdef), //
        42L,
        NetworkParameters.fromID(NetworkParameters.ID_REGTEST)
    );

    byte[] result = BridgeSerializationUtils.serializeFederation(federation);
    StringBuilder expectedBuilder = new StringBuilder();
    expectedBuilder.append("ff00abcdef"); // Creation time
    expectedBuilder.append("ff2a"); // Creation block number
    federation.getPublicKeys().stream().sorted(BtcECKey.PUBKEY_COMPARATOR).forEach(key -> {
        expectedBuilder.append("dd");
        expectedBuilder.append(Hex.toHexString(key.getPubKey()));
    });
    byte[] expected = Hex.decode(expectedBuilder.toString());
    Assert.assertTrue(Arrays.equals(expected, result));
}
 
Example 14
Project: powsybl-core   File: DoublePoint.java   Source Code and License Vote up 4 votes
@Override
public String toString() {
    return "DoublePoint(index=" + index + ", time=" + Instant.ofEpochMilli(time) + ", value=" + value + ")";
}
 
Example 15
Project: powsybl-core   File: TimeSeriesIndex.java   Source Code and License Vote up 4 votes
static Instant getInstantAt(TimeSeriesIndex index, int point) {
    return Instant.ofEpochMilli(index.getTimeAt(point));
}
 
Example 16
Project: powsybl-core   File: RegularTimeSeriesIndex.java   Source Code and License Vote up 4 votes
@Override
public String toString() {
    return "RegularTimeSeriesIndex(startTime=" + Instant.ofEpochMilli(startTime) + ", endTime=" + Instant.ofEpochMilli(endTime) +
            ", spacing=" + Duration.ofMillis(spacing) + ")";
}
 
Example 17
Project: openjdk-jdk10   File: TestInstant.java   Source Code and License Vote up 4 votes
@Test(dataProvider="sampleEpochMillis")
public void test_epochMillis(String name, long millis) {
    Instant t1 = Instant.ofEpochMilli(millis);
    long m = t1.toEpochMilli();
    assertEquals(millis, m, name);
}
 
Example 18
Project: buenojo   File: CustomAuditEventRepository.java   Source Code and License Vote up 4 votes
@Bean
public AuditEventRepository auditEventRepository() {
    return new AuditEventRepository() {

        private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";

        private static final String ANONYMOUS_USER = "anonymousUser";

        @Inject
        private AuditEventConverter auditEventConverter;

        @Override
        public List<AuditEvent> find(String principal, Date after) {
            Iterable<PersistentAuditEvent> persistentAuditEvents;
            if (principal == null && after == null) {
                persistentAuditEvents = persistenceAuditEventRepository.findAll();
            } else if (after == null) {
                persistentAuditEvents = persistenceAuditEventRepository.findByPrincipal(principal);
            } else {
                persistentAuditEvents =
                    persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfter(principal, LocalDateTime.from(after.toInstant()));
            }
            return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
        }

        @Override
        @Transactional(propagation = Propagation.REQUIRES_NEW)
        public void add(AuditEvent event) {
            if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
                !ANONYMOUS_USER.equals(event.getPrincipal().toString())) {

                PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
                persistentAuditEvent.setPrincipal(event.getPrincipal());
                persistentAuditEvent.setAuditEventType(event.getType());
                Instant instant = Instant.ofEpochMilli(event.getTimestamp().getTime());
                persistentAuditEvent.setAuditEventDate(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
                persistentAuditEvent.setData(auditEventConverter.convertDataToStrings(event.getData()));
                persistenceAuditEventRepository.save(persistentAuditEvent);
            }
        }
    };
}
 
Example 19
Project: openjdk-jdk10   File: TCKInstant.java   Source Code and License Vote up 4 votes
@Test(dataProvider="MillisInstantNoNanos")
public void factory_millis_long(long millis, long expectedSeconds, int expectedNanoOfSecond) {
    Instant t = Instant.ofEpochMilli(millis);
    assertEquals(t.getEpochSecond(), expectedSeconds);
    assertEquals(t.getNano(), expectedNanoOfSecond);
}
 
Example 20
Project: OpenJSharp   File: Calendar.java   Source Code and License Vote up 2 votes
/**
 * Converts this object to an {@link Instant}.
 * <p>
 * The conversion creates an {@code Instant} that represents the
 * same point on the time-line as this {@code Calendar}.
 *
 * @return the instant representing the same point on the time-line
 * @since 1.8
 */
public final Instant toInstant() {
    return Instant.ofEpochMilli(getTimeInMillis());
}