Search in sources :

Example 1 with WebhookEntityPk

use of org.orcid.persistence.jpa.entities.keys.WebhookEntityPk in project ORCID-Source by ORCID.

the class WebhookDaoTest method testFindWebhooksReadyToProcessWhenIsNotReadyForRetry.

@Test
@Rollback(true)
public void testFindWebhooksReadyToProcessWhenIsNotReadyForRetry() {
    Date now = new Date();
    WebhookEntityPk pk = new WebhookEntityPk();
    pk.setProfile(profileDao.find("4444-4444-4444-4443"));
    pk.setUri("http://nowhere.com/orcid/4444-4444-4444-4443");
    WebhookEntity webhook = webhookDao.find(pk);
    webhook.setLastFailed(new Date(now.getTime() - 120 * 1000));
    webhook.setFailedAttemptCount(1);
    webhookDao.merge(webhook);
    List<WebhookEntity> results = webhookDao.findWebhooksReadyToProcess(now, 5, 10);
    assertNotNull(results);
    assertEquals(0, results.size());
}
Also used : WebhookEntityPk(org.orcid.persistence.jpa.entities.keys.WebhookEntityPk) WebhookEntity(org.orcid.persistence.jpa.entities.WebhookEntity) Date(java.util.Date) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test) Rollback(org.springframework.test.annotation.Rollback)

Example 2 with WebhookEntityPk

use of org.orcid.persistence.jpa.entities.keys.WebhookEntityPk in project ORCID-Source by ORCID.

the class WebhookManagerImpl method processWebhooksInternal.

private void processWebhooksInternal() {
    // Log start time
    LOGGER.info("About to process webhooks");
    Date startTime = new Date();
    long count = webhookDaoReadOnly.countWebhooksReadyToProcess(startTime, retryDelayMinutes);
    LOGGER.info("Total number of webhooks ready to process={}", count);
    // Create thread pool of size determined by runtime property
    ExecutorService executorService = createThreadPoolForWebhooks();
    List<WebhookEntity> webhooks = new ArrayList<>(0);
    Map<WebhookEntityPk, WebhookEntity> mapOfpreviousBatch = null;
    int executedCount = 0;
    OUTER: do {
        mapOfpreviousBatch = WebhookEntity.mapById(webhooks);
        // Get chunk of webhooks to process for records that changed before
        // start time
        webhooks = webhookDaoReadOnly.findWebhooksReadyToProcess(startTime, retryDelayMinutes, WEBHOOKS_BATCH_SIZE);
        // Log the chunk size
        LOGGER.info("Found batch of {} webhooks to process", webhooks.size());
        int executedCountAtStartOfChunk = executedCount;
        // For each callback in chunk
        for (final WebhookEntity webhook : webhooks) {
            if (executedCount == maxPerRun) {
                LOGGER.info("Reached maxiumum of {} webhooks for this run", executedCount);
                break OUTER;
            }
            // Need to ignore anything in previous chunk
            if (mapOfpreviousBatch.containsKey(webhook.getId())) {
                LOGGER.debug("Skipping webhook as was in previous batch: {}", webhook.getId());
                continue;
            }
            // Submit job to thread pool
            executorService.execute(new Runnable() {

                public void run() {
                    processWebhookInTransaction(webhook);
                }
            });
            executedCount++;
        }
        if (executedCount == executedCountAtStartOfChunk) {
            LOGGER.info("No more webhooks added to pool, because all were in previous chunk");
            break;
        }
    } while (!webhooks.isEmpty());
    executorService.shutdown();
    try {
        LOGGER.info("Waiting for webhooks thread pool to finish");
        executorService.awaitTermination(120, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        LOGGER.warn("Received an interupt exception whilst waiting for the webhook processing complete", e);
    }
    LOGGER.info("Finished processing webhooks. Number of webhooks processed={}", executedCount);
}
Also used : WebhookEntityPk(org.orcid.persistence.jpa.entities.keys.WebhookEntityPk) WebhookEntity(org.orcid.persistence.jpa.entities.WebhookEntity) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) Date(java.util.Date)

Example 3 with WebhookEntityPk

use of org.orcid.persistence.jpa.entities.keys.WebhookEntityPk in project ORCID-Source by ORCID.

the class T2OrcidApiServiceDelegatorImpl method unregisterWebhook.

/**
 * Unregister a webhook from a profile. As with all calls, if the message
 * contains any other elements, a 400 Bad Request will be returned.
 *
 * @param orcid
 *            the identifier of the profile to unregister the webhook
 * @param uriInfo
 *            an uri object containing the webhook that will be unregistred
 * @return If successful, returns a 204 No content.
 */
@Override
@AccessControl(requiredScope = ScopePathType.WEBHOOK)
public Response unregisterWebhook(UriInfo uriInfo, String orcid, String webhookUri) {
    ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
    if (profile != null) {
        WebhookEntityPk webhookPk = new WebhookEntityPk(profile, webhookUri);
        WebhookEntity webhook = webhookManager.find(webhookPk);
        if (webhook == null) {
            Map<String, String> params = new HashMap<String, String>();
            params.put("orcid", orcid);
            params.put("uri", webhookUri);
            throw new OrcidWebhookNotFoundException(params);
        } else {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String clientId = null;
            if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
                OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
                clientId = authorizationRequest.getClientId();
            }
            // Check if user can unregister this webhook
            if (webhook.getClientDetails().getId().equals(clientId)) {
                webhookManager.delete(webhookPk);
                return Response.noContent().build();
            } else {
                // that webhook
                throw new OrcidForbiddenException(localeManager.resolveMessage("apiError.forbidden_unregister_webhook.exception"));
            }
        }
    } else {
        Map<String, String> params = new HashMap<String, String>();
        params.put("orcid", orcid);
        throw new OrcidNotFoundException(params);
    }
}
Also used : OrcidWebhookNotFoundException(org.orcid.core.exception.OrcidWebhookNotFoundException) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidForbiddenException(org.orcid.core.exception.OrcidForbiddenException) WebhookEntityPk(org.orcid.persistence.jpa.entities.keys.WebhookEntityPk) HashMap(java.util.HashMap) WebhookEntity(org.orcid.persistence.jpa.entities.WebhookEntity) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidNotFoundException(org.orcid.core.exception.OrcidNotFoundException) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 4 with WebhookEntityPk

use of org.orcid.persistence.jpa.entities.keys.WebhookEntityPk in project ORCID-Source by ORCID.

the class T2OrcidApiServiceDelegatorImpl method registerWebhook.

/**
 * Register a new webhook to the profile. As with all calls, if the message
 * contains any other elements, a 400 Bad Request will be returned.
 *
 * @param orcid
 *            the identifier of the profile to add the webhook
 * @param uriInfo
 *            an uri object containing the webhook
 * @return If successful, returns a 2xx.
 */
@Override
@AccessControl(requiredScope = ScopePathType.WEBHOOK)
public Response registerWebhook(UriInfo uriInfo, String orcid, String webhookUri) {
    @SuppressWarnings("unused") URI validatedWebhookUri = null;
    try {
        validatedWebhookUri = new URI(webhookUri);
    } catch (URISyntaxException e) {
        Object[] params = { webhookUri };
        throw new OrcidBadRequestException(localeManager.resolveMessage("apiError.badrequest_incorrect_webhook.exception", params));
    }
    ProfileEntity profile = profileEntityCacheManager.retrieve(orcid);
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    ClientDetailsEntity clientDetails = null;
    String clientId = null;
    if (OAuth2Authentication.class.isAssignableFrom(authentication.getClass())) {
        OAuth2Request authorizationRequest = ((OAuth2Authentication) authentication).getOAuth2Request();
        clientId = authorizationRequest.getClientId();
        clientDetails = clientDetailsManager.findByClientId(clientId);
    }
    if (profile != null && clientDetails != null) {
        WebhookEntityPk webhookPk = new WebhookEntityPk(profile, webhookUri);
        WebhookEntity webhook = webhookManager.find(webhookPk);
        boolean isNew = webhook == null;
        if (isNew) {
            webhook = new WebhookEntity();
            webhook.setProfile(profile);
            webhook.setDateCreated(new Date());
            webhook.setEnabled(true);
            webhook.setUri(webhookUri);
            webhook.setClientDetails(clientDetails);
        }
        webhookManager.update(webhook);
        return isNew ? Response.created(uriInfo.getAbsolutePath()).build() : Response.noContent().build();
    } else if (profile == null) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("orcid", orcid);
        throw new OrcidNotFoundException(params);
    } else {
        Map<String, String> params = new HashMap<String, String>();
        params.put("client", clientId);
        throw new OrcidClientNotFoundException(params);
    }
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) WebhookEntityPk(org.orcid.persistence.jpa.entities.keys.WebhookEntityPk) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) Date(java.util.Date) SubmissionDate(org.orcid.jaxb.model.message.SubmissionDate) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) OrcidBadRequestException(org.orcid.core.exception.OrcidBadRequestException) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Authentication(org.springframework.security.core.Authentication) WebhookEntity(org.orcid.persistence.jpa.entities.WebhookEntity) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) OrcidNotFoundException(org.orcid.core.exception.OrcidNotFoundException) Map(java.util.Map) HashMap(java.util.HashMap) OrcidClientNotFoundException(org.orcid.core.exception.OrcidClientNotFoundException) AccessControl(org.orcid.core.security.visibility.aop.AccessControl)

Example 5 with WebhookEntityPk

use of org.orcid.persistence.jpa.entities.keys.WebhookEntityPk in project ORCID-Source by ORCID.

the class WebhookDaoTest method testMergeFindAndRemove.

@Test
@Rollback(true)
public void testMergeFindAndRemove() {
    ProfileEntity profile = new ProfileEntity("1234-1234-1234-1234");
    profileDao.merge(profile);
    ProfileEntity clientProfile = new ProfileEntity("4444-4444-4444-4449");
    profileDao.merge(clientProfile);
    ClientDetailsEntity clientDetails = new ClientDetailsEntity();
    clientDetails.setGroupProfileId(clientProfile.getId());
    clientDetails.setId(clientProfile.getId());
    clientDetailsDao.merge(clientDetails);
    WebhookEntity webhook = new WebhookEntity();
    webhook.setProfile(profile);
    webhook.setUri("http://semantico.com/orcid/1234");
    webhook.setClientDetails(clientDetails);
    webhookDao.merge(webhook);
    WebhookEntityPk pk = new WebhookEntityPk();
    pk.setProfile(profile);
    pk.setUri("http://semantico.com/orcid/1234");
    WebhookEntity retrieved = webhookDao.find(pk);
    assertNotNull(retrieved);
    assertEquals("1234-1234-1234-1234", retrieved.getProfile().getId());
    assertEquals("http://semantico.com/orcid/1234", retrieved.getUri());
    assertEquals("4444-4444-4444-4449", retrieved.getClientDetails().getClientId());
    assertTrue(retrieved.isEnabled());
    assertEquals(0, retrieved.getFailedAttemptCount());
    assertNull(retrieved.getLastFailed());
    webhookDao.remove(pk);
    retrieved = webhookDao.find(pk);
    assertNull(retrieved);
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) WebhookEntityPk(org.orcid.persistence.jpa.entities.keys.WebhookEntityPk) WebhookEntity(org.orcid.persistence.jpa.entities.WebhookEntity) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) DBUnitTest(org.orcid.test.DBUnitTest) Test(org.junit.Test) Rollback(org.springframework.test.annotation.Rollback)

Aggregations

WebhookEntity (org.orcid.persistence.jpa.entities.WebhookEntity)5 WebhookEntityPk (org.orcid.persistence.jpa.entities.keys.WebhookEntityPk)5 Date (java.util.Date)3 ProfileEntity (org.orcid.persistence.jpa.entities.ProfileEntity)3 HashMap (java.util.HashMap)2 Test (org.junit.Test)2 OrcidNotFoundException (org.orcid.core.exception.OrcidNotFoundException)2 AccessControl (org.orcid.core.security.visibility.aop.AccessControl)2 ClientDetailsEntity (org.orcid.persistence.jpa.entities.ClientDetailsEntity)2 DBUnitTest (org.orcid.test.DBUnitTest)2 Authentication (org.springframework.security.core.Authentication)2 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)2 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)2 Rollback (org.springframework.test.annotation.Rollback)2 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 ArrayList (java.util.ArrayList)1 Map (java.util.Map)1 ExecutorService (java.util.concurrent.ExecutorService)1 OrcidBadRequestException (org.orcid.core.exception.OrcidBadRequestException)1