Search in sources :

Example 56 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project candlepin by candlepin.

the class EntitlementRules method filterPools.

@Override
@SuppressWarnings("checkstyle:indentation")
public List<Pool> filterPools(Consumer consumer, List<Pool> pools, boolean showAll) {
    JsonJsContext args = new JsonJsContext(objectMapper);
    Map<String, ValidationResult> resultMap = new HashMap<>();
    ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
    if (!ctype.isType(ConsumerTypeEnum.SHARE)) {
        Stream<PoolDTO> poolStream = pools == null ? Stream.empty() : pools.stream().map(this.translator.getStreamMapper(Pool.class, PoolDTO.class));
        Stream<EntitlementDTO> entStream = consumer.getEntitlements() == null ? Stream.empty() : consumer.getEntitlements().stream().map(this.translator.getStreamMapper(Entitlement.class, EntitlementDTO.class));
        args.put("consumer", this.translator.translate(consumer, ConsumerDTO.class));
        args.put("hostConsumer", this.translator.translate(getHost(consumer, pools), ConsumerDTO.class));
        args.put("consumerEntitlements", entStream.collect(Collectors.toSet()));
        args.put("standalone", config.getBoolean(ConfigProperties.STANDALONE));
        args.put("pools", poolStream.collect(Collectors.toSet()));
        args.put("caller", CallerType.LIST_POOLS.getLabel());
        args.put("log", log, false);
        String json = jsRules.runJsFunction(String.class, "validate_pools_list", args);
        TypeReference<Map<String, ValidationResult>> typeref = new TypeReference<Map<String, ValidationResult>>() {
        };
        try {
            resultMap = objectMapper.toObject(json, typeref);
        } catch (Exception e) {
            throw new RuleExecutionException(e);
        }
    }
    List<Pool> filteredPools = new LinkedList<>();
    for (Pool pool : pools) {
        ValidationResult result;
        if (ctype.isType(ConsumerTypeEnum.SHARE)) {
            result = new ValidationResult();
            resultMap.put(pool.getId(), result);
            validatePoolSharingEligibility(result, pool);
        } else {
            result = resultMap.get(pool.getId());
        }
        finishValidation(result, pool, 1);
        if (result.isSuccessful() && (!result.hasWarnings() || showAll)) {
            filteredPools.add(pool);
        } else if (log.isDebugEnabled()) {
            log.debug("Omitting pool due to failed rules: " + pool.getId());
            if (result.hasErrors()) {
                log.debug("\tErrors: " + result.getErrors());
            }
            if (result.hasWarnings()) {
                log.debug("\tWarnings: " + result.getWarnings());
            }
        }
    }
    return filteredPools;
}
Also used : HashMap(java.util.HashMap) PoolDTO(org.candlepin.dto.rules.v1.PoolDTO) ValidationResult(org.candlepin.policy.ValidationResult) RuleExecutionException(org.candlepin.policy.js.RuleExecutionException) LinkedList(java.util.LinkedList) EntitlementDTO(org.candlepin.dto.rules.v1.EntitlementDTO) ConsumerDTO(org.candlepin.dto.rules.v1.ConsumerDTO) JsonJsContext(org.candlepin.policy.js.JsonJsContext) Pool(org.candlepin.model.Pool) TypeReference(com.fasterxml.jackson.core.type.TypeReference) RuleExecutionException(org.candlepin.policy.js.RuleExecutionException) ConsumerType(org.candlepin.model.ConsumerType) Map(java.util.Map) HashMap(java.util.HashMap)

Example 57 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project joynr by bmwcarit.

the class SubscriptionManagerTest method registerSubscriptionWithoutExpiryDate.

@Test
public void registerSubscriptionWithoutExpiryDate() throws JoynrSendBufferFullException, JoynrMessageNotSentException, JsonGenerationException, JsonMappingException, IOException {
    class IntegerReference extends TypeReference<Integer> {
    }
    AttributeSubscribeInvocation request = new AttributeSubscribeInvocation(attributeName, IntegerReference.class, attributeSubscriptionCallback, qosWithoutExpiryDate, future);
    subscriptionId = request.getSubscriptionId();
    subscriptionManager.registerAttributeSubscription(fromParticipantId, Sets.newHashSet(toDiscoveryEntry), request);
    verify(attributeSubscriptionDirectory).put(Mockito.anyString(), Mockito.eq(attributeSubscriptionCallback));
    verify(subscriptionStates).put(Mockito.anyString(), Mockito.any(PubSubState.class));
    verify(cleanupScheduler, never()).schedule(Mockito.any(Runnable.class), Mockito.anyLong(), Mockito.any(TimeUnit.class));
    verify(subscriptionEndFutures, never()).put(Mockito.anyString(), Mockito.any(ScheduledFuture.class));
    verify(dispatcher).sendSubscriptionRequest(eq(fromParticipantId), eq(Sets.newHashSet(toDiscoveryEntry)), any(SubscriptionRequest.class), any(MessagingQos.class));
}
Also used : SubscriptionRequest(joynr.SubscriptionRequest) MessagingQos(io.joynr.messaging.MessagingQos) TimeUnit(java.util.concurrent.TimeUnit) TypeReference(com.fasterxml.jackson.core.type.TypeReference) AttributeSubscribeInvocation(io.joynr.proxy.invocation.AttributeSubscribeInvocation) ScheduledFuture(java.util.concurrent.ScheduledFuture) Test(org.junit.Test)

Example 58 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project joynr by bmwcarit.

the class SubscriptionManagerTest method registerSubscription.

@SuppressWarnings("unchecked")
@Test
public void registerSubscription() throws JoynrSendBufferFullException, JoynrMessageNotSentException, JsonGenerationException, JsonMappingException, IOException {
    class IntegerReference extends TypeReference<Integer> {
    }
    Future<String> future = mock(Future.class);
    AttributeSubscribeInvocation subscriptionRequest = new AttributeSubscribeInvocation(attributeName, IntegerReference.class, attributeSubscriptionCallback, qos, future);
    subscriptionManager.registerAttributeSubscription(fromParticipantId, Sets.newHashSet(toDiscoveryEntry), subscriptionRequest);
    subscriptionId = subscriptionRequest.getSubscriptionId();
    verify(attributeSubscriptionDirectory).put(Mockito.anyString(), Mockito.eq(attributeSubscriptionCallback));
    verify(subscriptionStates).put(Mockito.anyString(), Mockito.any(PubSubState.class));
    verify(cleanupScheduler).schedule(Mockito.any(Runnable.class), Mockito.eq(qos.getExpiryDateMs()), Mockito.eq(TimeUnit.MILLISECONDS));
    verify(subscriptionEndFutures, Mockito.times(1)).put(Mockito.eq(subscriptionId), Mockito.any(ScheduledFuture.class));
    verify(dispatcher).sendSubscriptionRequest(eq(fromParticipantId), eq(Sets.newHashSet(toDiscoveryEntry)), any(SubscriptionRequest.class), any(MessagingQos.class));
}
Also used : SubscriptionRequest(joynr.SubscriptionRequest) MessagingQos(io.joynr.messaging.MessagingQos) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Matchers.anyString(org.mockito.Matchers.anyString) AttributeSubscribeInvocation(io.joynr.proxy.invocation.AttributeSubscribeInvocation) ScheduledFuture(java.util.concurrent.ScheduledFuture) Test(org.junit.Test)

Example 59 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project muikku by otavanopisto.

the class EntityCacheEvictor method onWebhookNotificationEvent.

public void onWebhookNotificationEvent(@Observes WebhookNotificationEvent event) {
    try {
        List<String> evictTypePaths = cacheConfigs.getEvictTypePaths(event.getType());
        Map<String, String> data = null;
        try {
            data = new ObjectMapper().readValue(event.getData(), new TypeReference<Map<String, String>>() {
            });
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Could not parse webhook notification data", e);
            return;
        }
        for (AbstractEntityCache cache : caches) {
            try {
                Pattern pattern = Pattern.compile("\\{[a-zA-Z]*\\}");
                for (String evictTypePath : evictTypePaths) {
                    String path = evictTypePath;
                    Matcher matcher = pattern.matcher(path);
                    while (matcher.find()) {
                        String variable = StringUtils.substring(matcher.group(0), 1, -1);
                        String value = data.get(variable);
                        if (value != null) {
                            path = matcher.replaceFirst(value);
                        } else {
                            logger.log(Level.SEVERE, String.format("Failed to parse path %s", evictTypePath));
                            break;
                        }
                        matcher = pattern.matcher(path);
                    }
                    cache.remove(path);
                }
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Failed to evict caches", e);
                return;
            }
        }
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Cache evict crashed", e);
    }
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) TypeReference(com.fasterxml.jackson.core.type.TypeReference) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException)

Example 60 with TypeReference

use of com.fasterxml.jackson.core.type.TypeReference in project AJSC by att.

the class RefresheableRESTErrorMap method refresh.

public static void refresh(File file) throws Exception {
    try {
        System.out.println("Loading error to http status code map...");
        ObjectMapper mapper = new ObjectMapper();
        TypeReference<HashMap<String, RestError>> typeRef = new TypeReference<HashMap<String, RestError>>() {
        };
        HashMap<String, RestError> map = mapper.readValue(file, typeRef);
        wrapped.set(map);
        System.out.println("File " + file.getName() + " is loaded into the error map");
    } catch (Exception e) {
        System.err.println("File " + file.getName() + " cannot be loaded into the error map " + e.getMessage());
        throw new Exception("Error reading REST error map file " + file.getName(), e);
    } finally {
        System.out.println("Done with load...");
    }
}
Also used : HashMap(java.util.HashMap) RestError(ajsc.exceptions.RestError) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

TypeReference (com.fasterxml.jackson.core.type.TypeReference)316 IOException (java.io.IOException)130 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)113 Test (org.junit.Test)95 ArrayList (java.util.ArrayList)74 Map (java.util.Map)74 List (java.util.List)60 HashMap (java.util.HashMap)58 File (java.io.File)34 TextPageLink (org.thingsboard.server.common.data.page.TextPageLink)27 Collectors (java.util.stream.Collectors)25 InputStream (java.io.InputStream)23 JsonNode (com.fasterxml.jackson.databind.JsonNode)19 ImmutableMap (com.google.common.collect.ImmutableMap)19 lombok.val (lombok.val)18 Matchers.containsString (org.hamcrest.Matchers.containsString)17 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)14 Collections (java.util.Collections)13 ISE (org.apache.druid.java.util.common.ISE)12 URL (java.net.URL)10