Search in sources :

Example 46 with Consumer

use of java.util.function.Consumer in project kylo by Teradata.

the class JcrFeedProvider method addPostFeedChangeAction.

/**
 * Registers an action that produces a feed change event upon a successful transaction commit.
 *
 * @param feed the feed to being created
 */
private void addPostFeedChangeAction(Feed feed, ChangeType changeType) {
    Feed.State state = feed.getState();
    Feed.ID id = feed.getId();
    String feedName = feed.getQualifiedName();
    final Principal principal = SecurityContextHolder.getContext().getAuthentication();
    Consumer<Boolean> action = (success) -> {
        if (success) {
            FeedChange change = new FeedChange(changeType, feedName, feedName, id, state);
            FeedChangeEvent event = new FeedChangeEvent(change, DateTime.now(), principal);
            metadataEventService.notify(event);
        }
    };
    JcrMetadataAccess.addPostTransactionAction(action);
}
Also used : ID(com.thinkbiganalytics.metadata.api.feed.Feed.ID) EntityUtil(com.thinkbiganalytics.metadata.modeshape.common.EntityUtil) Category(com.thinkbiganalytics.metadata.api.category.Category) DatasourceNotFoundException(com.thinkbiganalytics.metadata.api.datasource.DatasourceNotFoundException) ChangeType(com.thinkbiganalytics.metadata.api.event.MetadataChange.ChangeType) Metric(com.thinkbiganalytics.metadata.sla.api.Metric) ServiceLevelAgreementActionConfiguration(com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreementActionConfiguration) QueryResult(javax.jcr.query.QueryResult) FeedChange(com.thinkbiganalytics.metadata.api.event.feed.FeedChange) Obligation(com.thinkbiganalytics.metadata.sla.api.Obligation) AbstractMetadataCriteria(com.thinkbiganalytics.metadata.modeshape.AbstractMetadataCriteria) FeedProvider(com.thinkbiganalytics.metadata.api.feed.FeedProvider) JcrQueryUtil(com.thinkbiganalytics.metadata.modeshape.support.JcrQueryUtil) SecurityRole(com.thinkbiganalytics.security.role.SecurityRole) FeedAccessControl(com.thinkbiganalytics.metadata.api.feed.security.FeedAccessControl) JcrDatasource(com.thinkbiganalytics.metadata.modeshape.datasource.JcrDatasource) Map(java.util.Map) FeedPropertyChangeEvent(com.thinkbiganalytics.metadata.api.event.feed.FeedPropertyChangeEvent) AccessController(com.thinkbiganalytics.security.AccessController) Pageable(org.springframework.data.domain.Pageable) UserFieldDescriptors(com.thinkbiganalytics.metadata.modeshape.common.UserFieldDescriptors) JcrAllowedEntityActionsProvider(com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedEntityActionsProvider) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ServiceLevelAgreement(com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement) FeedDestination(com.thinkbiganalytics.metadata.api.feed.FeedDestination) PreconditionBuilder(com.thinkbiganalytics.metadata.api.feed.PreconditionBuilder) CategoryNotFoundException(com.thinkbiganalytics.metadata.api.category.CategoryNotFoundException) CategoryDetails(com.thinkbiganalytics.metadata.modeshape.category.CategoryDetails) Session(javax.jcr.Session) FeedOpsAccessControlProvider(com.thinkbiganalytics.metadata.api.feed.security.FeedOpsAccessControlProvider) Set(java.util.Set) MetadataEventService(com.thinkbiganalytics.metadata.api.event.MetadataEventService) Collectors(java.util.stream.Collectors) FeedCriteria(com.thinkbiganalytics.metadata.api.feed.FeedCriteria) Serializable(java.io.Serializable) SecurityRoleProvider(com.thinkbiganalytics.security.role.SecurityRoleProvider) List(java.util.List) Principal(java.security.Principal) Predicate(com.google.common.base.Predicate) CategoryProvider(com.thinkbiganalytics.metadata.api.category.CategoryProvider) JcrServiceLevelAgreement(com.thinkbiganalytics.metadata.modeshape.sla.JcrServiceLevelAgreement) JcrAllowedActions(com.thinkbiganalytics.metadata.modeshape.security.action.JcrAllowedActions) Optional(java.util.Optional) BaseJcrProvider(com.thinkbiganalytics.metadata.modeshape.BaseJcrProvider) PropertyChange(com.thinkbiganalytics.metadata.api.event.feed.PropertyChange) JcrMetadataAccess(com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess) NodeIterator(javax.jcr.NodeIterator) JcrEntity(com.thinkbiganalytics.metadata.modeshape.common.JcrEntity) Feed(com.thinkbiganalytics.metadata.api.feed.Feed) HashMap(java.util.HashMap) MetadataRepositoryException(com.thinkbiganalytics.metadata.modeshape.MetadataRepositoryException) ServiceLevelAgreementBuilder(com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementBuilder) AllowedActions(com.thinkbiganalytics.security.action.AllowedActions) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) ObligationGroupBuilder(com.thinkbiganalytics.metadata.sla.spi.ObligationGroupBuilder) RepositoryException(javax.jcr.RepositoryException) Node(javax.jcr.Node) FeedChangeEvent(com.thinkbiganalytics.metadata.api.event.feed.FeedChangeEvent) FeedSource(com.thinkbiganalytics.metadata.api.feed.FeedSource) Nonnull(javax.annotation.Nonnull) FeedNotFoundException(com.thinkbiganalytics.metadata.api.feed.FeedNotFoundException) Datasource(com.thinkbiganalytics.metadata.api.datasource.Datasource) FeedNameUtil(com.thinkbiganalytics.support.FeedNameUtil) DateTime(org.joda.time.DateTime) ServiceLevelAgreementProvider(com.thinkbiganalytics.metadata.sla.spi.ServiceLevelAgreementProvider) UserFieldDescriptor(com.thinkbiganalytics.metadata.api.extension.UserFieldDescriptor) JcrServiceLevelAgreementProvider(com.thinkbiganalytics.metadata.modeshape.sla.JcrServiceLevelAgreementProvider) FeedManagerTemplate(com.thinkbiganalytics.metadata.api.template.FeedManagerTemplate) HadoopSecurityGroup(com.thinkbiganalytics.metadata.api.security.HadoopSecurityGroup) Consumer(java.util.function.Consumer) JcrCategory(com.thinkbiganalytics.metadata.modeshape.category.JcrCategory) ID(com.thinkbiganalytics.metadata.api.feed.Feed.ID) Condition(com.thinkbiganalytics.metadata.sla.api.ObligationGroup.Condition) JcrUtil(com.thinkbiganalytics.metadata.modeshape.support.JcrUtil) ObligationBuilder(com.thinkbiganalytics.metadata.sla.spi.ObligationBuilder) JcrObject(com.thinkbiganalytics.metadata.modeshape.common.JcrObject) DatasourceProvider(com.thinkbiganalytics.metadata.api.datasource.DatasourceProvider) VersionProviderMixin(com.thinkbiganalytics.metadata.modeshape.common.mixin.VersionProviderMixin) Collections(java.util.Collections) FeedChange(com.thinkbiganalytics.metadata.api.event.feed.FeedChange) FeedChangeEvent(com.thinkbiganalytics.metadata.api.event.feed.FeedChangeEvent) Principal(java.security.Principal) Feed(com.thinkbiganalytics.metadata.api.feed.Feed)

Example 47 with Consumer

use of java.util.function.Consumer in project felix by apache.

the class FELIX3057_EmptyServiceReferenceArray method testWithoutIndex.

@SuppressWarnings("unchecked")
public void testWithoutIndex() throws Exception {
    // backup currently configured filter index
    BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
    m_systemConf = context.getProperty(DependencyManager.SERVICEREGISTRY_CACHE_INDICES);
    // Reset filter indices
    Consumer<String> reset = (Consumer<String>) System.getProperties().get("org.apache.felix.dependencymanager.filterindex.reset");
    // clear filter index
    reset.accept(null);
    // no filter index used
    executeTest(context);
    // reset filer index configured in our bnd.bnd
    reset.accept(m_systemConf);
}
Also used : Consumer(java.util.function.Consumer) BundleContext(org.osgi.framework.BundleContext)

Example 48 with Consumer

use of java.util.function.Consumer in project openremote by openremote.

the class KNXConnection method connect.

public synchronized void connect() {
    if (connectionStatus == ConnectionStatus.CONNECTED || connectionStatus == ConnectionStatus.CONNECTING) {
        LOG.finest("Already connected or connection in progress");
        return;
    }
    onConnectionStatusChanged(ConnectionStatus.CONNECTING);
    InetSocketAddress localEndPoint;
    InetSocketAddress remoteEndPoint = new InetSocketAddress(this.gatewayIp, this.remotePort);
    try {
        TPSettings tpSettings = new TPSettings(new IndividualAddress(this.localKNXAddress));
        if (StringUtils.isNotBlank(this.localIp)) {
            localEndPoint = new InetSocketAddress(this.localIp, 0);
        } else {
            InetAddress localHost = InetAddress.getLocalHost();
            localEndPoint = new InetSocketAddress(localHost, 0);
        }
        if (this.connectionType.equals("TUNNELLING")) {
            knxLink = KNXNetworkLinkIP.newTunnelingLink(localEndPoint, remoteEndPoint, this.useNat, tpSettings);
        } else {
            knxLink = KNXNetworkLinkIP.newRoutingLink(localEndPoint.getAddress(), remoteEndPoint.getAddress(), tpSettings);
        }
        if (knxLink.isOpen()) {
            LOG.fine("Successfully connected to: " + gatewayIp + ":" + port);
            processCommunicator = new ProcessCommunicatorImpl(knxLink);
            processCommunicator.addProcessListener(this);
            knxLink.addLinkListener(this);
            reconnectTask = null;
            reconnectDelayMilliseconds = INITIAL_RECONNECT_DELAY_MILLIS;
            onConnectionStatusChanged(ConnectionStatus.CONNECTED);
            // Get the values of all registered group addresses
            LOG.fine("Initialising group address values");
            synchronized (groupAddressConsumerMap) {
                groupAddressConsumerMap.forEach((groupAddress, datapointConsumerList) -> {
                    if (!datapointConsumerList.isEmpty()) {
                        // Take first data point for the group address and request the value
                        Pair<StateDP, Consumer<Value>> datapointConsumer = datapointConsumerList.get(0);
                        getGroupAddressValue(datapointConsumer.key.getMainAddress(), datapointConsumer.key.getPriority());
                    }
                });
            }
        } else {
            LOG.log(Level.INFO, "Connection error");
            // Failed to connect so schedule reconnection attempt
            scheduleReconnect();
        }
    } catch (final KNXException | InterruptedException e) {
        LOG.log(Level.INFO, "Connection error", e.getMessage());
        scheduleReconnect();
    } catch (final UnknownHostException e) {
        LOG.log(Level.INFO, "Connection error", e.getMessage());
    }
}
Also used : Consumer(java.util.function.Consumer) UnknownHostException(java.net.UnknownHostException) ProcessCommunicatorImpl(tuwien.auto.calimero.process.ProcessCommunicatorImpl) InetSocketAddress(java.net.InetSocketAddress) TPSettings(tuwien.auto.calimero.link.medium.TPSettings) StateDP(tuwien.auto.calimero.datapoint.StateDP) InetAddress(java.net.InetAddress)

Example 49 with Consumer

use of java.util.function.Consumer in project openremote by openremote.

the class UsersFacade method query.

@Override
public Users.RestrictedQuery query() {
    Users.RestrictedQuery query = new Users.RestrictedQuery() {

        @Override
        public Users.RestrictedQuery tenant(UserQuery.TenantPredicate tenantPredicate) {
            if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))
                return super.tenant(tenantPredicate);
            throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
        }

        @Override
        public Users.RestrictedQuery asset(UserQuery.AssetPredicate assetPredicate) {
            if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))
                return super.asset(assetPredicate);
            if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
                return super.asset(assetPredicate);
            // TODO: should only be allowed if asset belongs to tenant
            }
            if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
                return super.asset(assetPredicate);
            // TODO: should only be allowed if restricted asset is descendant of scope's asset
            }
            throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");
        }

        @Override
        public List<String> getResults() {
            return notificationService.findAllUsersWithToken(this);
        }

        @Override
        public void applyResults(Consumer<List<String>> usersIdListConsumer) {
            usersIdListConsumer.accept(getResults());
        }
    };
    if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
        query.tenantPredicate = new UserQuery.TenantPredicate(rulesEngineId.getRealmId().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId)));
    }
    if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {
        String assetId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId));
        ServerAsset restrictedAsset = assetStorageService.find(assetId, true);
        if (restrictedAsset == null) {
            // deployment is removed and the problem resolved.
            throw new IllegalStateException("Asset is no longer available: " + rulesEngineId);
        }
        query.assetPredicate = new UserQuery.AssetPredicate(assetId);
    }
    return query;
}
Also used : ServerAsset(org.openremote.manager.asset.ServerAsset) Consumer(java.util.function.Consumer) UserQuery(org.openremote.model.user.UserQuery)

Example 50 with Consumer

use of java.util.function.Consumer in project nifi by apache.

the class AsyncRequestManager method submitRequest.

@Override
public void submitRequest(final String type, final String requestId, final AsynchronousWebRequest<T> request, final Consumer<AsynchronousWebRequest<T>> task) {
    Objects.requireNonNull(type);
    Objects.requireNonNull(requestId);
    Objects.requireNonNull(request);
    Objects.requireNonNull(task);
    // before adding to the request map, purge any old requests. Must do this by creating a List of ID's
    // and then removing those ID's one-at-a-time in order to avoid ConcurrentModificationException.
    final Date oneMinuteAgo = new Date(System.currentTimeMillis() - requestExpirationMillis);
    final List<String> completedRequestIds = requests.entrySet().stream().filter(entry -> entry.getValue().isComplete()).filter(entry -> entry.getValue().getLastUpdated().before(oneMinuteAgo)).map(Map.Entry::getKey).collect(Collectors.toList());
    completedRequestIds.stream().forEach(id -> requests.remove(id));
    final int requestCount = requests.size();
    if (requestCount > maxConcurrentRequests) {
        throw new IllegalStateException("There are already " + requestCount + " update requests for variable registries. " + "Cannot issue any more requests until the older ones are deleted or expire");
    }
    final String key = getKey(type, requestId);
    final AsynchronousWebRequest<T> existing = this.requests.putIfAbsent(key, request);
    if (existing != null) {
        throw new IllegalArgumentException("A requests already exists with this ID and type");
    }
    threadPool.submit(new Runnable() {

        @Override
        public void run() {
            try {
                task.accept(request);
            } catch (final Exception e) {
                logger.error("Failed to perform asynchronous task", e);
                request.setFailureReason("Encountered unexpected error when performing asynchronous task: " + e);
            }
        }
    });
}
Also used : Logger(org.slf4j.Logger) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Date(java.util.Date) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) ConcurrentMap(java.util.concurrent.ConcurrentMap) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) NiFiUser(org.apache.nifi.authorization.user.NiFiUser) Map(java.util.Map) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorService(java.util.concurrent.ExecutorService) Date(java.util.Date) ResourceNotFoundException(org.apache.nifi.web.ResourceNotFoundException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map)

Aggregations

Consumer (java.util.function.Consumer)908 List (java.util.List)445 ArrayList (java.util.ArrayList)288 Test (org.junit.Test)250 Map (java.util.Map)228 IOException (java.io.IOException)223 Collectors (java.util.stream.Collectors)205 Collections (java.util.Collections)185 Arrays (java.util.Arrays)181 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)163 TimeUnit (java.util.concurrent.TimeUnit)157 HashMap (java.util.HashMap)152 Set (java.util.Set)149 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)146 Optional (java.util.Optional)132 Collection (java.util.Collection)127 Function (java.util.function.Function)119 CountDownLatch (java.util.concurrent.CountDownLatch)116 File (java.io.File)112 AtomicReference (java.util.concurrent.atomic.AtomicReference)111