io.gravitee.common.utils.UUID Java Examples

The following examples show how to use io.gravitee.common.utils.UUID. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VertxHttpServerRequest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public VertxHttpServerRequest(HttpServerRequest httpServerRequest) {
    this.httpServerRequest = httpServerRequest;
    this.timestamp = System.currentTimeMillis();
    this.id = UUID.toString(UUID.random());
    this.transactionId = UUID.toString(UUID.random());
    this.contextPath = httpServerRequest.path() != null ? httpServerRequest.path().split("/")[0] : null;

    this.metrics = Metrics.on(timestamp).build();
    this.metrics.setRequestId(id());
    this.metrics.setHttpMethod(method());
    this.metrics.setLocalAddress(localAddress());
    this.metrics.setRemoteAddress(remoteAddress());
    this.metrics.setHost(httpServerRequest.host());
    this.metrics.setUri(uri());
    this.metrics.setUserAgent(httpServerRequest.getHeader(HttpHeaders.USER_AGENT));
}
 
Example #2
Source File: TransactionProcessorTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPropagateSameTransactionIdWithCustomHeader() throws InterruptedException {
    final CountDownLatch lock = new CountDownLatch(1);

    String transactionId = UUID.toString(UUID.random());

    request.headers().set(CUSTOM_TRANSACTION_ID_HEADER, transactionId);
    new TransactionProcessor(CUSTOM_TRANSACTION_ID_HEADER)
            .handler(context -> {
        Assert.assertNotNull(context.request().transactionId());
        Assert.assertEquals(transactionId, context.request().transactionId());
        Assert.assertEquals(transactionId, context.request().headers().getFirst(CUSTOM_TRANSACTION_ID_HEADER));
        Assert.assertEquals(transactionId, context.request().metrics().getTransactionId());
        Assert.assertEquals(context.request().transactionId(), response.headers().getFirst(CUSTOM_TRANSACTION_ID_HEADER));
        lock.countDown();
    }).handle(context);

    Assert.assertTrue(lock.await(10000, TimeUnit.MILLISECONDS));
}
 
Example #3
Source File: TransactionProcessorTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHaveTransactionIdWithCustomHeader() throws InterruptedException {
    final CountDownLatch lock = new CountDownLatch(1);

    Mockito.when(request.id()).thenReturn(UUID.toString(UUID.random()));

    new TransactionProcessor(CUSTOM_TRANSACTION_ID_HEADER)
            .handler(context -> {
        Assert.assertNotNull(context.request().transactionId());
        Assert.assertEquals(context.request().transactionId(), context.request().headers().getFirst(CUSTOM_TRANSACTION_ID_HEADER));
        Assert.assertEquals(context.request().transactionId(), context.request().metrics().getTransactionId());
        Assert.assertEquals(context.request().transactionId(), response.headers().getFirst(CUSTOM_TRANSACTION_ID_HEADER));
        lock.countDown();
    }).handle(context);

    Assert.assertTrue(lock.await(10000, TimeUnit.MILLISECONDS));
}
 
Example #4
Source File: TransactionProcessorTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPropagateSameTransactionId() throws InterruptedException {
    final CountDownLatch lock = new CountDownLatch(1);

    String transactionId = UUID.toString(UUID.random());

    request.headers().set(TransactionProcessor.DEFAULT_TRANSACTIONAL_ID_HEADER, transactionId);
    new TransactionProcessor()
            .handler(context -> {
        Assert.assertNotNull(context.request().transactionId());
        Assert.assertEquals(transactionId, context.request().transactionId());
        Assert.assertEquals(transactionId, context.request().headers().getFirst(TransactionProcessor.DEFAULT_TRANSACTIONAL_ID_HEADER));
        Assert.assertEquals(transactionId, context.request().metrics().getTransactionId());
        Assert.assertEquals(context.request().transactionId(), response.headers().getFirst(TransactionProcessor.DEFAULT_TRANSACTIONAL_ID_HEADER));
        lock.countDown();
    }).handle(context);

    Assert.assertTrue(lock.await(10000, TimeUnit.MILLISECONDS));
}
 
Example #5
Source File: TransactionProcessorTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHaveTransactionId() throws InterruptedException {
    final CountDownLatch lock = new CountDownLatch(1);

    Mockito.when(request.id()).thenReturn(UUID.toString(UUID.random()));

    new TransactionProcessor()
            .handler(context -> {
                    Assert.assertNotNull(context.request().transactionId());
                    Assert.assertEquals(context.request().transactionId(), context.request().headers().getFirst(TransactionProcessor.DEFAULT_TRANSACTIONAL_ID_HEADER));
                    Assert.assertEquals(context.request().transactionId(), context.request().metrics().getTransactionId());
                    Assert.assertEquals(context.request().transactionId(), response.headers().getFirst(TransactionProcessor.DEFAULT_TRANSACTIONAL_ID_HEADER));
                    lock.countDown();
            })
            .handle(context);

    Assert.assertTrue(lock.await(10000, TimeUnit.MILLISECONDS));
}
 
Example #6
Source File: HeartbeatService.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
private Event prepareEvent() {
    Event event = new Event();
    event.setId(UUID.toString(UUID.random()));
    event.setType(EventType.GATEWAY_STARTED);
    event.setCreatedAt(new Date());
    event.setEnvironmentId("DEFAULT");
    event.setUpdatedAt(event.getCreatedAt());
    Map<String, String> properties = new HashMap<>();
    properties.put("id", node.id());
    final String now = Long.toString(event.getCreatedAt().getTime());
    properties.put("started_at", now);
    properties.put("last_heartbeat_at", now);
    event.setProperties(properties);

    InstanceEventPayload instance = createInstanceInfo();

    try {
        String payload = objectMapper.writeValueAsString(instance);
        event.setPayload(payload);
    } catch (JsonProcessingException jsex) {
        LOGGER.error("An error occurs while transforming instance information into JSON", jsex);
    }
    return event;
}
 
Example #7
Source File: ClientRegistrationServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private ClientRegistrationProvider convert(NewClientRegistrationProviderEntity newClientRegistrationProvider) {
    ClientRegistrationProvider provider = new ClientRegistrationProvider();
    provider.setId(UUID.toString(UUID.random()));
    provider.setName(newClientRegistrationProvider.getName());
    provider.setDescription(newClientRegistrationProvider.getDescription());
    provider.setDiscoveryEndpoint(newClientRegistrationProvider.getDiscoveryEndpoint());
    provider.setRenewClientSecretSupport(newClientRegistrationProvider.isRenewClientSecretSupport());
    provider.setRenewClientSecretMethod(newClientRegistrationProvider.getRenewClientSecretMethod());
    provider.setRenewClientSecretEndpoint(newClientRegistrationProvider.getRenewClientSecretEndpoint());
    provider.setSoftwareId(newClientRegistrationProvider.getSoftwareId());

    if (newClientRegistrationProvider.getInitialAccessTokenType() == InitialAccessTokenType.CLIENT_CREDENTIALS) {
        provider.setInitialAccessTokenType(ClientRegistrationProvider.InitialAccessTokenType.CLIENT_CREDENTIALS);
        provider.setClientId(newClientRegistrationProvider.getClientId());
        provider.setClientSecret(newClientRegistrationProvider.getClientSecret());
        provider.setScopes(newClientRegistrationProvider.getScopes());
    } else {
        provider.setInitialAccessTokenType(ClientRegistrationProvider.InitialAccessTokenType.INITIAL_ACCESS_TOKEN);
        provider.setInitialAccessToken(newClientRegistrationProvider.getInitialAccessToken());
    }

    return provider;
}
 
Example #8
Source File: AlertServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private AlertTrigger convert(final UpdateAlertTriggerEntity alertEntity) {
    final AlertTrigger alert = new AlertTrigger();
    alert.setId(UUID.toString(UUID.random()));
    alert.setName(alertEntity.getName());
    alert.setDescription(alertEntity.getDescription());
    alert.setEnabled(alertEntity.isEnabled());
    alert.setSeverity(alertEntity.getSeverity().name());

    try {
        String definition = mapper.writeValueAsString(alertEntity);
        alert.setDefinition(definition);
    } catch (Exception ex) {
        LOGGER.error("An unexpected error occurs while transforming the alert trigger definition into string", ex);
    }

    return alert;
}
 
Example #9
Source File: AlertServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private AlertTrigger convert(final NewAlertTriggerEntity alertEntity) {
    final AlertTrigger alert = new AlertTrigger();
    alert.setId(UUID.toString(UUID.random()));
    alertEntity.setId(alert.getId());
    alert.setName(alertEntity.getName());
    alert.setDescription(alertEntity.getDescription());
    alert.setReferenceId(alertEntity.getReferenceId());
    alert.setReferenceType(alertEntity.getReferenceType().name());
    alert.setEnabled(alertEntity.isEnabled());
    alert.setType(alertEntity.getType());
    alert.setSeverity(alertEntity.getSeverity().name());

    try {
        String definition = mapper.writeValueAsString(alertEntity);
        alert.setDefinition(definition);
    } catch (Exception ex) {
        LOGGER.error("An unexpected error occurs while transforming the alert trigger definition into string", ex);
    }

    return alert;
}
 
Example #10
Source File: AlertServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
private void handleAlertNotificationCommand(AlertNotificationCommand command) {
    try {
        AlertEvent alertEvent = new AlertEvent();

        alertEvent.setId(UUID.toString(UUID.random()));
        alertEvent.setAlert(command.getTrigger());
        alertEvent.setCreatedAt(new Date(command.getTimestamp()));
        alertEvent.setUpdatedAt(alertEvent.getCreatedAt());
        alertEvent.setMessage(command.getMessage());

        alertEventRepository.create(alertEvent);
    } catch (TechnicalException ex) {
        final String message = "An error occurs while trying to create an alert event from command {}" + command;
        LOGGER.error(message, ex);
        throw new TechnicalManagementException(message, ex);
    }
}
 
Example #11
Source File: TokenServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
private Token convert(final NewTokenEntity tokenEntity, final TokenReferenceType referenceType,
                      final String referenceId, final String encodedToken) {
    final Token token = new Token();
    token.setId(UUID.toString(UUID.random()));
    token.setToken(encodedToken);
    token.setName(tokenEntity.getName());
    token.setCreatedAt(new Date());
    token.setReferenceType(referenceType.name());
    token.setReferenceId(referenceId);
    return token;
}
 
Example #12
Source File: JettyHttpServerRequest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public JettyHttpServerRequest(HttpServletRequest httpServerRequest) {
    this.httpServerRequest = httpServerRequest;
    this.timestamp = System.currentTimeMillis();
    this.id = UUID.toString(UUID.random());
    this.transactionId = UUID.toString(UUID.random());
    this.contextPath = httpServerRequest.getContextPath() != null ? httpServerRequest.getContextPath().split("/")[0] : null;
}
 
Example #13
Source File: TransactionHandler.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    String transactionId = context.request().headers().get(transactionHeader);

    if (transactionId == null) {
        transactionId = UUID.toString(UUID.random());
        context.request().headers().set(transactionHeader, transactionId);
    }
    context.response().headers().set(transactionHeader,transactionId);

    context.next();
}
 
Example #14
Source File: EntrypointServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private Single<Entrypoint> createInternal(Entrypoint toCreate, User principal) {

        Date now = new Date();

        toCreate.setId(UUID.random().toString());
        toCreate.setCreatedAt(now);
        toCreate.setUpdatedAt(now);

        return validate(toCreate)
                .andThen(entrypointRepository.create(toCreate)
                        .doOnSuccess(entrypoint -> auditService.report(AuditBuilder.builder(EntrypointAuditBuilder.class).entrypoint(entrypoint).principal(principal).type(EventType.ENTRYPOINT_CREATED)))
                        .doOnError(throwable -> auditService.report(AuditBuilder.builder(EntrypointAuditBuilder.class).referenceId(toCreate.getOrganizationId()).principal(principal).type(EventType.ENTRYPOINT_CREATED).throwable(throwable))));
    }
 
Example #15
Source File: VertxHttpServerRequest.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
public VertxHttpServerRequest(HttpServerRequest httpServerRequest) {
    this.httpServerRequest = httpServerRequest;
    this.timestamp = System.currentTimeMillis();
    this.id = UUID.toString(UUID.random());

    this.metrics = Metrics.on(timestamp).build();
    this.metrics.setRequestId(id());
    this.metrics.setHttpMethod(method());
    this.metrics.setLocalAddress(localAddress());
    this.metrics.setRemoteAddress(remoteAddress());
    this.metrics.setHost(httpServerRequest.host());
    this.metrics.setUri(uri());
    this.metrics.setUserAgent(httpServerRequest.getHeader(HttpHeaders.USER_AGENT));
}
 
Example #16
Source File: AuditServiceImpl.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Async
protected void create(Audit.AuditReferenceType referenceType, String referenceId, Map<Audit.AuditProperties,String> properties,
                      Audit.AuditEvent event, Date createdAt,
                      Object oldValue, Object newValue) {

    Audit audit = new Audit();
    audit.setId(UUID.toString(UUID.random()));
    audit.setCreatedAt(createdAt);

    final UserDetails authenticatedUser = getAuthenticatedUser();
    final String user;
    if (authenticatedUser != null && "token".equals(authenticatedUser.getSource())) {
        user = userService.findById(authenticatedUser.getUsername()).getDisplayName() +
                " - (using token \"" + authenticatedUser.getSourceId() + "\")";
    } else {
        user = getAuthenticatedUsernameOrSystem();
    }
    audit.setUser(user);

    if (properties != null) {
        Map<String, String> stringStringMap = new HashMap<>(properties.size());
        properties.forEach((auditProperties, s) -> stringStringMap.put(auditProperties.name(), s));
        audit.setProperties(stringStringMap);
    }

    audit.setReferenceType(referenceType);
    audit.setReferenceId(referenceId);
    audit.setEvent(event.name());

    ObjectNode oldNode = oldValue == null
            ? mapper.createObjectNode()
            : mapper.convertValue(oldValue, ObjectNode.class).remove(Arrays.asList("updatedAt", "createdAt"));
    ObjectNode newNode = newValue == null
            ? mapper.createObjectNode()
            : mapper.convertValue(newValue, ObjectNode.class).remove(Arrays.asList("updatedAt", "createdAt"));

    audit.setPatch(JsonDiff.asJson(oldNode, newNode).toString());

    try {
        auditRepository.create(audit);
    } catch (TechnicalException e) {
        LOGGER.error("Error occurs during the creation of an Audit Log {}.", e);
    }
}
 
Example #17
Source File: RandomString.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
public static String generate() {
    return UUID.toString(UUID.random());
}
 
Example #18
Source File: RandomString.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
public static String generate() {
    return UUID.toString(UUID.random());
}