Search in sources :

Example 41 with Objects

use of java.util.Objects in project grakn by graknlabs.

the class InferenceRule method propagateConstraints.

/**
 * @param parentAtom atom containing constraints (parent)
 * @param unifier unifier unifying parent with the rule
 * @return rule with propagated constraints from parent
 */
public InferenceRule propagateConstraints(Atom parentAtom, Unifier unifier) {
    if (!parentAtom.isRelation() && !parentAtom.isResource())
        return this;
    Atom headAtom = head.getAtom();
    Set<Atomic> bodyAtoms = new HashSet<>(body.getAtoms());
    // transfer value predicates
    parentAtom.getPredicates(ValuePredicate.class).flatMap(vp -> vp.unify(unifier).stream()).forEach(bodyAtoms::add);
    // if head is a resource merge vps into head
    if (headAtom.isResource() && ((ResourceAtom) headAtom).getMultiPredicate().isEmpty()) {
        ResourceAtom resourceHead = (ResourceAtom) headAtom;
        Set<ValuePredicate> innerVps = parentAtom.getInnerPredicates(ValuePredicate.class).flatMap(vp -> vp.unify(unifier).stream()).peek(bodyAtoms::add).collect(toSet());
        headAtom = ResourceAtom.create(headAtom.getPattern(), headAtom.getPredicateVariable(), resourceHead.getRelationVariable(), resourceHead.getTypeId(), innerVps, headAtom.getParentQuery());
    }
    Set<TypeAtom> unifiedTypes = parentAtom.getTypeConstraints().flatMap(type -> type.unify(unifier).stream()).collect(toSet());
    // set rule body types to sub types of combined query+rule types
    Set<TypeAtom> ruleTypes = body.getAtoms(TypeAtom.class).filter(t -> !t.isRelation()).collect(toSet());
    Set<TypeAtom> allTypes = Sets.union(unifiedTypes, ruleTypes);
    allTypes.stream().filter(ta -> {
        SchemaConcept schemaConcept = ta.getSchemaConcept();
        SchemaConcept subType = allTypes.stream().map(Atom::getSchemaConcept).filter(Objects::nonNull).filter(t -> ReasonerUtils.supers(t).contains(schemaConcept)).findFirst().orElse(null);
        return schemaConcept == null || subType == null;
    }).forEach(t -> bodyAtoms.add(t.copy(body)));
    return new InferenceRule(ReasonerQueries.atomic(headAtom), ReasonerQueries.create(bodyAtoms, tx), ruleId, tx);
}
Also used : PatternAdmin(ai.grakn.graql.admin.PatternAdmin) UnifierType(ai.grakn.graql.internal.reasoner.UnifierType) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) ReasonerQueryImpl(ai.grakn.graql.internal.reasoner.query.ReasonerQueryImpl) SchemaConcept(ai.grakn.concept.SchemaConcept) Answer(ai.grakn.graql.admin.Answer) QueryStateBase(ai.grakn.graql.internal.reasoner.state.QueryStateBase) Rule(ai.grakn.concept.Rule) ResolutionState(ai.grakn.graql.internal.reasoner.state.ResolutionState) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ConceptId(ai.grakn.concept.ConceptId) Collectors.toSet(java.util.stream.Collectors.toSet) QueryCache(ai.grakn.graql.internal.reasoner.cache.QueryCache) Patterns(ai.grakn.graql.internal.pattern.Patterns) ValuePredicate(ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate) Conjunction(ai.grakn.graql.admin.Conjunction) MultiUnifier(ai.grakn.graql.admin.MultiUnifier) Set(java.util.Set) ReasonerUtils(ai.grakn.graql.internal.reasoner.utils.ReasonerUtils) Sets(com.google.common.collect.Sets) Objects(java.util.Objects) Atomic(ai.grakn.graql.admin.Atomic) TypeAtom(ai.grakn.graql.internal.reasoner.atom.binary.TypeAtom) List(java.util.List) ReasonerQueries(ai.grakn.graql.internal.reasoner.query.ReasonerQueries) RuleState(ai.grakn.graql.internal.reasoner.state.RuleState) EmbeddedGraknTx(ai.grakn.kb.internal.EmbeddedGraknTx) Var(ai.grakn.graql.Var) VarPatternAdmin(ai.grakn.graql.admin.VarPatternAdmin) ReasonerAtomicQuery(ai.grakn.graql.internal.reasoner.query.ReasonerAtomicQuery) Unifier(ai.grakn.graql.admin.Unifier) ResourceAtom(ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom) ResourceAtom(ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom) TypeAtom(ai.grakn.graql.internal.reasoner.atom.binary.TypeAtom) Atomic(ai.grakn.graql.admin.Atomic) SchemaConcept(ai.grakn.concept.SchemaConcept) Atom(ai.grakn.graql.internal.reasoner.atom.Atom) TypeAtom(ai.grakn.graql.internal.reasoner.atom.binary.TypeAtom) ResourceAtom(ai.grakn.graql.internal.reasoner.atom.binary.ResourceAtom) ValuePredicate(ai.grakn.graql.internal.reasoner.atom.predicate.ValuePredicate) Objects(java.util.Objects) HashSet(java.util.HashSet)

Example 42 with Objects

use of java.util.Objects in project carbon-apimgt by wso2.

the class ApiFileDAOImpl method getAPIs.

/**
 * @see ApiDAO#getAPIs(Set, String)
 */
@Override
public List<API> getAPIs(Set<String> roles, String user) throws APIMgtDAOException {
    File[] files = new File(storagePath).listFiles();
    List<API> apiList = new ArrayList<>();
    final FilenameFilter filenameFilter = (dir, name) -> (name.endsWith(APIMgtConstants.APIFileUtilConstants.JSON_EXTENSION) && name.contains(APIMgtConstants.APIFileUtilConstants.API_DEFINITION_FILE_PREFIX) && !dir.isHidden());
    if (files != null) {
        for (File file : files) {
            apiList.add((API) fetchObject(file, FileApi.class, filenameFilter));
        }
    }
    apiList.removeIf(Objects::isNull);
    return apiList;
}
Also used : FilenameFilter(java.io.FilenameFilter) DedicatedGateway(org.wso2.carbon.apimgt.core.models.DedicatedGateway) LoggerFactory(org.slf4j.LoggerFactory) Rating(org.wso2.carbon.apimgt.core.models.Rating) JsonReader(com.google.gson.stream.JsonReader) APIFileUtils(org.wso2.carbon.apimgt.core.util.APIFileUtils) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Map(java.util.Map) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIMgtConstants(org.wso2.carbon.apimgt.core.util.APIMgtConstants) Logger(org.slf4j.Logger) API(org.wso2.carbon.apimgt.core.models.API) Set(java.util.Set) ExceptionCodes(org.wso2.carbon.apimgt.core.exception.ExceptionCodes) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) Comment(org.wso2.carbon.apimgt.core.models.Comment) Objects(java.util.Objects) List(java.util.List) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) FileApi(org.wso2.carbon.apimgt.core.models.FileApi) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) InputStream(java.io.InputStream) FilenameFilter(java.io.FilenameFilter) ArrayList(java.util.ArrayList) Objects(java.util.Objects) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) File(java.io.File)

Example 43 with Objects

use of java.util.Objects in project TinyKeePass by sorz.

the class AuthActivity method onDatabaseOpened.

@Override
protected void onDatabaseOpened() {
    StructureParser.Result result = parseStructure();
    KeePassFile keePass = KeePassStorage.get(this);
    SearchIndex index = new SearchIndex(keePass);
    StringBuilder queryBuilder = new StringBuilder();
    result.title.forEach(title -> queryBuilder.append(title).append(' '));
    Stream<Entry> entryStream = index.search(queryBuilder.toString()).map(keePass::getEntryByUUID);
    FillResponse.Builder responseBuilder = new FillResponse.Builder();
    // add matched entities
    entryStream.map(entry -> AutofillUtils.buildDataset(this, entry, result)).filter(Objects::nonNull).limit(MAX_NUM_CANDIDATE_ENTRIES).forEach(responseBuilder::addDataset);
    // add "show all" item
    RemoteViews presentation = AutofillUtils.getRemoteViews(this, getString(R.string.autofill_item_show_all), R.drawable.ic_more_horiz_gray_24dp);
    presentation.setTextColor(R.id.textView, getColor(R.color.hint));
    Dataset.Builder datasetBuilder = new Dataset.Builder(presentation).setAuthentication(EntrySelectActivity.getAuthIntentSenderForResponse(this));
    result.allAutofillIds().forEach(id -> datasetBuilder.setValue(id, null));
    responseBuilder.addDataset(datasetBuilder.build());
    setFillResponse(responseBuilder.build());
    finish();
}
Also used : RemoteViews(android.widget.RemoteViews) Context(android.content.Context) Dataset(android.service.autofill.Dataset) KeyException(java.security.KeyException) KeePassFile(de.slackspace.openkeepass.domain.KeePassFile) R(org.sorz.lab.tinykeepass.R) SearchIndex(org.sorz.lab.tinykeepass.search.SearchIndex) Intent(android.content.Intent) RequiresApi(android.support.annotation.RequiresApi) PendingIntent(android.app.PendingIntent) Objects(java.util.Objects) IntentSender(android.content.IntentSender) Stream(java.util.stream.Stream) FillResponse(android.service.autofill.FillResponse) KeePassStorage(org.sorz.lab.tinykeepass.keepass.KeePassStorage) Build(android.os.Build) Entry(de.slackspace.openkeepass.domain.Entry) SearchIndex(org.sorz.lab.tinykeepass.search.SearchIndex) Dataset(android.service.autofill.Dataset) FillResponse(android.service.autofill.FillResponse) Entry(de.slackspace.openkeepass.domain.Entry) RemoteViews(android.widget.RemoteViews) Objects(java.util.Objects) KeePassFile(de.slackspace.openkeepass.domain.KeePassFile)

Example 44 with Objects

use of java.util.Objects in project camel by apache.

the class EtcdServiceDiscovery method getServices.

protected List<ServiceDefinition> getServices(Predicate<EtcdServiceDefinition> filter) {
    List<ServiceDefinition> servers = Collections.emptyList();
    if (isRunAllowed()) {
        try {
            final EtcdConfiguration conf = getConfiguration();
            final EtcdKeyGetRequest request = getClient().get(conf.getServicePath()).recursive();
            if (conf.hasTimeout()) {
                request.timeout(conf.getTimeout(), TimeUnit.SECONDS);
            }
            final EtcdKeysResponse response = request.send().get();
            if (Objects.nonNull(response.node) && !response.node.nodes.isEmpty()) {
                servers = response.node.nodes.stream().map(node -> node.value).filter(ObjectHelper::isNotEmpty).map(this::nodeFromString).filter(Objects::nonNull).filter(filter).sorted(EtcdServiceDefinition.COMPARATOR).collect(Collectors.toList());
            }
        } catch (Exception e) {
            throw new RuntimeCamelException(e);
        }
    }
    return servers;
}
Also used : EtcdKeysResponse(mousio.etcd4j.responses.EtcdKeysResponse) RuntimeCamelException(org.apache.camel.RuntimeCamelException) Logger(org.slf4j.Logger) EtcdClient(mousio.etcd4j.EtcdClient) Predicate(java.util.function.Predicate) ServiceDefinition(org.apache.camel.cloud.ServiceDefinition) EtcdConfiguration(org.apache.camel.component.etcd.EtcdConfiguration) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) EtcdKeyGetRequest(mousio.etcd4j.requests.EtcdKeyGetRequest) LoggerFactory(org.slf4j.LoggerFactory) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) DefaultServiceDiscovery(org.apache.camel.impl.cloud.DefaultServiceDiscovery) ObjectHelper(org.apache.camel.util.ObjectHelper) Collections(java.util.Collections) EtcdHelper(org.apache.camel.component.etcd.EtcdHelper) ObjectHelper(org.apache.camel.util.ObjectHelper) EtcdKeyGetRequest(mousio.etcd4j.requests.EtcdKeyGetRequest) EtcdConfiguration(org.apache.camel.component.etcd.EtcdConfiguration) Objects(java.util.Objects) EtcdKeysResponse(mousio.etcd4j.responses.EtcdKeysResponse) RuntimeCamelException(org.apache.camel.RuntimeCamelException) ServiceDefinition(org.apache.camel.cloud.ServiceDefinition) RuntimeCamelException(org.apache.camel.RuntimeCamelException)

Example 45 with Objects

use of java.util.Objects in project opennms by OpenNMS.

the class GraphMLMetaTopologyFactory method updated.

@Override
public void updated(String pid, @SuppressWarnings("rawtypes") Dictionary properties) throws ConfigurationException {
    LOG.debug("updated(String, Dictionary) invoked");
    String location = (String) properties.get(TOPOLOGY_LOCATION);
    if (!m_serviceRegistration.containsKey(pid)) {
        LOG.debug("Service with pid '{}' is new. Register {}", pid, GraphMLMetaTopologyProvider.class.getSimpleName());
        final Dictionary<String, Object> metaData = new Hashtable<>();
        metaData.put(Constants.SERVICE_PID, pid);
        if (properties.get(LABEL) != null) {
            metaData.put(LABEL, properties.get(LABEL));
        }
        // Expose the MetaTopologyProvider
        try {
            final GraphMLMetaTopologyProvider metaTopologyProvider = new GraphMLMetaTopologyProvider(m_serviceAccessor);
            metaTopologyProvider.setTopologyLocation(location);
            metaTopologyProvider.reload();
            registerService(pid, MetaTopologyProvider.class, metaTopologyProvider, metaData);
            // Create and register additional services
            final Set<String> iconKeys = metaTopologyProvider.getGraphProviders().stream().map(GraphProvider::getNamespace).flatMap(eachNamespace -> metaTopologyProvider.getRawTopologyProvider(eachNamespace).getVertices().stream()).map(Vertex::getIconKey).filter(Objects::nonNull).collect(Collectors.toSet());
            registerService(pid, IconRepository.class, new GraphMLIconRepository(iconKeys));
            // Create an OSGi aware script engine manager
            final ScriptEngineManager scriptEngineManager = new OSGiScriptEngineManager(m_bundleContext);
            metaTopologyProvider.getGraphProviders().forEach(it -> {
                // Find Topology Provider
                final GraphMLTopologyProvider rawTopologyProvider = metaTopologyProvider.getRawTopologyProvider(it.getNamespace());
                // EdgeStatusProvider
                registerService(pid, EdgeStatusProvider.class, new GraphMLEdgeStatusProvider(rawTopologyProvider, scriptEngineManager, m_serviceAccessor));
                // SearchProvider
                registerService(pid, SearchProvider.class, new GraphMLSearchProvider(rawTopologyProvider));
                // Vertex Status Provider
                // Only add status provider if explicitly set in GraphML document
                this.buildStatusProvider(metaTopologyProvider, scriptEngineManager, rawTopologyProvider).ifPresent(statusProvider -> registerService(pid, StatusProvider.class, statusProvider));
            });
        } catch (InvalidGraphException | IOException e) {
            LOG.error("An error occurred while loading GraphMLTopology from file {}. Ignoring...", location, e);
        }
    } else {
        LOG.warn("Service with pid '{}' updated. Updating is not supported. Ignoring...");
    }
}
Also used : GraphMLSearchProvider(org.opennms.features.topology.plugins.topo.graphml.GraphMLSearchProvider) Constants(org.osgi.framework.Constants) Vertex(org.opennms.features.topology.api.topo.Vertex) LoggerFactory(org.slf4j.LoggerFactory) EdgeStatusProvider(org.opennms.features.topology.api.topo.EdgeStatusProvider) OSGiScriptEngineManager(org.opennms.features.osgi.script.OSGiScriptEngineManager) GraphMLPropagateVertexStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLPropagateVertexStatusProvider) Lists(com.google.common.collect.Lists) ConfigurationException(org.osgi.service.cm.ConfigurationException) Map(java.util.Map) InvalidGraphException(org.opennms.features.graphml.model.InvalidGraphException) IconRepository(org.opennms.features.topology.api.IconRepository) Hashtable(java.util.Hashtable) SearchProvider(org.opennms.features.topology.api.topo.SearchProvider) GraphProvider(org.opennms.features.topology.api.topo.GraphProvider) ServiceRegistration(org.osgi.framework.ServiceRegistration) ManagedServiceFactory(org.osgi.service.cm.ManagedServiceFactory) Logger(org.slf4j.Logger) Set(java.util.Set) ScriptEngineManager(javax.script.ScriptEngineManager) GraphMLTopologyProvider(org.opennms.features.topology.plugins.topo.graphml.GraphMLTopologyProvider) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Maps(com.google.common.collect.Maps) MetaTopologyProvider(org.opennms.features.topology.api.topo.MetaTopologyProvider) BundleContext(org.osgi.framework.BundleContext) Objects(java.util.Objects) List(java.util.List) StatusProvider(org.opennms.features.topology.api.topo.StatusProvider) GraphMLDefaultVertexStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLDefaultVertexStatusProvider) GraphMLEdgeStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLEdgeStatusProvider) Optional(java.util.Optional) GraphMLMetaTopologyProvider(org.opennms.features.topology.plugins.topo.graphml.GraphMLMetaTopologyProvider) GraphMLScriptVertexStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLScriptVertexStatusProvider) Dictionary(java.util.Dictionary) Vertex(org.opennms.features.topology.api.topo.Vertex) GraphMLTopologyProvider(org.opennms.features.topology.plugins.topo.graphml.GraphMLTopologyProvider) OSGiScriptEngineManager(org.opennms.features.osgi.script.OSGiScriptEngineManager) InvalidGraphException(org.opennms.features.graphml.model.InvalidGraphException) Hashtable(java.util.Hashtable) EdgeStatusProvider(org.opennms.features.topology.api.topo.EdgeStatusProvider) GraphMLPropagateVertexStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLPropagateVertexStatusProvider) StatusProvider(org.opennms.features.topology.api.topo.StatusProvider) GraphMLDefaultVertexStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLDefaultVertexStatusProvider) GraphMLEdgeStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLEdgeStatusProvider) GraphMLScriptVertexStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLScriptVertexStatusProvider) GraphMLMetaTopologyProvider(org.opennms.features.topology.plugins.topo.graphml.GraphMLMetaTopologyProvider) OSGiScriptEngineManager(org.opennms.features.osgi.script.OSGiScriptEngineManager) ScriptEngineManager(javax.script.ScriptEngineManager) IOException(java.io.IOException) GraphMLEdgeStatusProvider(org.opennms.features.topology.plugins.topo.graphml.status.GraphMLEdgeStatusProvider) GraphProvider(org.opennms.features.topology.api.topo.GraphProvider) GraphMLSearchProvider(org.opennms.features.topology.plugins.topo.graphml.GraphMLSearchProvider)

Aggregations

Objects (java.util.Objects)83 List (java.util.List)45 Map (java.util.Map)37 Collectors (java.util.stream.Collectors)32 ArrayList (java.util.ArrayList)30 Set (java.util.Set)30 IOException (java.io.IOException)22 HashMap (java.util.HashMap)21 Optional (java.util.Optional)19 Collections (java.util.Collections)18 LoggerFactory (org.slf4j.LoggerFactory)17 Stream (java.util.stream.Stream)16 Logger (org.slf4j.Logger)16 HashSet (java.util.HashSet)14 Collection (java.util.Collection)13 InputStream (java.io.InputStream)12 ImmutableSet (com.google.common.collect.ImmutableSet)10 Result (ddf.catalog.data.Result)9 TimeUnit (java.util.concurrent.TimeUnit)9 Metacard (ddf.catalog.data.Metacard)8