diff options
Diffstat (limited to 'catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl')
8 files changed, 597 insertions, 74 deletions
diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java index 65f4314b26..6a67a99fcf 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/AuditingDao.java @@ -20,15 +20,7 @@ package org.openecomp.sdc.be.dao.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.annotation.PostConstruct; - +import fj.data.Either; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; @@ -38,23 +30,24 @@ import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum; import org.openecomp.sdc.be.resources.data.auditing.AuditingGenericEvent; import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants; import org.openecomp.sdc.be.resources.data.auditing.ResourceAdminEvent; -import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum; +import org.openecomp.sdc.common.datastructure.AuditingFieldsKey; import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.*; +import java.util.Map.Entry; @Component("auditingDao") public class AuditingDao extends ESTimeBasedDao { - private static final String SERVICE_INSTANCE_ID_FIELD = AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID + private static final String SERVICE_INSTANCE_ID_FIELD = AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID .getDisplayName(); // "serviceInstanceId"; - private static final String STATUS_FIELD = AuditingFieldsKeysEnum.AUDIT_STATUS.getDisplayName(); // "status"; - private static final String ACTION_FIELD = AuditingFieldsKeysEnum.AUDIT_ACTION.getDisplayName(); // "action"; - private static final String DISTRIBUTION_ID_FIELD = AuditingFieldsKeysEnum.AUDIT_DISTRIBUTION_ID.getDisplayName(); // "distributionId"; - private static Logger log = LoggerFactory.getLogger(AuditingDao.class.getName()); + private static final String STATUS_FIELD = AuditingFieldsKey.AUDIT_STATUS.getDisplayName(); // "status"; + private static final String ACTION_FIELD = AuditingFieldsKey.AUDIT_ACTION.getDisplayName(); // "action"; + private static final String DISTRIBUTION_ID_FIELD = AuditingFieldsKey.AUDIT_DISTRIBUTION_ID.getDisplayName(); // "distributionId"; + private static Logger log = Logger.getLogger(AuditingDao.class.getName()); public static final String AUDITING_INDEX = "auditingevents"; @PostConstruct @@ -70,12 +63,12 @@ public class AuditingDao extends ESTimeBasedDao { return AUDITING_INDEX; } - public ActionStatus addRecord(Map<AuditingFieldsKeysEnum, Object> params, String type) { + public ActionStatus addRecord(Map<AuditingFieldsKey, Object> params, String type) { // TODO rhalili - remove? check debugEnabled? - Map<String, Object> displayFields = new HashMap<String, Object>(); + Map<String, Object> displayFields = new HashMap<>(); StringBuilder sb = new StringBuilder(); - for (Entry<AuditingFieldsKeysEnum, Object> entry : params.entrySet()) { + for (Entry<AuditingFieldsKey, Object> entry : params.entrySet()) { displayFields.put(entry.getKey().getDisplayName(), entry.getValue()); sb.append(entry.getKey().getDisplayName()).append(" = ").append(entry.getValue()).append(","); } @@ -118,7 +111,7 @@ public class AuditingDao extends ESTimeBasedDao { return Either.left(remainingElements); } else { log.debug("not found distribution statuses for did {}", did); - remainingElements = new ArrayList<ESTimeBasedEvent>(); + remainingElements = new ArrayList<>(); return Either.left(remainingElements); } @@ -126,7 +119,7 @@ public class AuditingDao extends ESTimeBasedDao { public Either<List<ESTimeBasedEvent>, ActionStatus> getServiceDistributionStatusesList(String serviceInstanceId) { - List<ESTimeBasedEvent> resList = new ArrayList<ESTimeBasedEvent>(); + List<ESTimeBasedEvent> resList = new ArrayList<>(); QueryBuilder componentNameMatch = QueryBuilders.matchQuery(SERVICE_INSTANCE_ID_FIELD, serviceInstanceId); QueryBuilder componentVersionMatch = QueryBuilders.matchQuery(ACTION_FIELD, AuditingActionEnum.DISTRIBUTION_STATE_CHANGE_REQUEST.getName()); @@ -185,12 +178,12 @@ public class AuditingDao extends ESTimeBasedDao { } public Either<List<ESTimeBasedEvent>, ActionStatus> getFilteredResourceAdminAuditingEvents( - Map<AuditingFieldsKeysEnum, Object> filterMap) { + Map<AuditingFieldsKey, Object> filterMap) { - Iterator<Entry<AuditingFieldsKeysEnum, Object>> filterItr = filterMap.entrySet().iterator(); + Iterator<Entry<AuditingFieldsKey, Object>> filterItr = filterMap.entrySet().iterator(); BoolQueryBuilder boolQuery = QueryBuilders.boolQuery(); while (filterItr.hasNext()) { - Entry<AuditingFieldsKeysEnum, Object> curr = filterItr.next(); + Entry<AuditingFieldsKey, Object> curr = filterItr.next(); boolQuery = boolQuery.must(QueryBuilders.termQuery(curr.getKey().getDisplayName(), curr.getValue())); } @@ -235,25 +228,25 @@ public class AuditingDao extends ESTimeBasedDao { } - private void populateCommonFields(Map<AuditingFieldsKeysEnum, Object> params, + private void populateCommonFields(Map<AuditingFieldsKey, Object> params, AuditingGenericEvent timeBasedIndexedData) { - String dateStr = (String) params.get(AuditingFieldsKeysEnum.AUDIT_TIMESTAMP); + String dateStr = (String) params.get(AuditingFieldsKey.AUDIT_TIMESTAMP); if (dateStr != null) { timeBasedIndexedData.setTimestamp(dateStr); } - timeBasedIndexedData.setAction((String) params.get(AuditingFieldsKeysEnum.AUDIT_ACTION)); - Object statusObj = params.get(AuditingFieldsKeysEnum.AUDIT_STATUS); + timeBasedIndexedData.setAction((String) params.get(AuditingFieldsKey.AUDIT_ACTION)); + Object statusObj = params.get(AuditingFieldsKey.AUDIT_STATUS); // For BC. status was Integer and is String if (statusObj != null) { timeBasedIndexedData.setStatus(String.valueOf(statusObj)); } else { timeBasedIndexedData.setStatus(null); } - // timeBasedIndexedData.setStatus((String)params.get(AuditingFieldsKeysEnum.AUDIT_STATUS)); - timeBasedIndexedData.setDesc((String) params.get(AuditingFieldsKeysEnum.AUDIT_DESC)); + // timeBasedIndexedData.setStatus((String)params.get(AuditingFieldsKey.AUDIT_STATUS)); + timeBasedIndexedData.setDesc((String) params.get(AuditingFieldsKey.AUDIT_DESC)); timeBasedIndexedData - .setServiceInstanceId((String) params.get(AuditingFieldsKeysEnum.AUDIT_SERVICE_INSTANCE_ID)); - timeBasedIndexedData.setRequestId((String) params.get(AuditingFieldsKeysEnum.AUDIT_REQUEST_ID)); + .setServiceInstanceId((String) params.get(AuditingFieldsKey.AUDIT_SERVICE_INSTANCE_ID)); + timeBasedIndexedData.setRequestId((String) params.get(AuditingFieldsKey.AUDIT_REQUEST_ID)); } } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java index 985875e200..c3dc886f85 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESCatalogDAO.java @@ -20,14 +20,8 @@ package org.openecomp.sdc.be.dao.impl; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; - -import javax.annotation.PostConstruct; - +import com.fasterxml.jackson.core.JsonProcessingException; +import fj.data.Either; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.unit.TimeValue; @@ -39,19 +33,23 @@ import org.openecomp.sdc.be.dao.api.ResourceUploadStatus; import org.openecomp.sdc.be.resources.data.ESArtifactData; import org.openecomp.sdc.be.resources.exception.ResourceDAOException; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.JsonProcessingException; - -import fj.data.Either; +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; @Component("resource-dao") public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO { - private static Logger log = LoggerFactory.getLogger(ESCatalogDAO.class.getName()); - private static Logger healthCheckLogger = LoggerFactory.getLogger("elasticsearch.healthcheck"); + private static Logger log = Logger.getLogger(ESCatalogDAO.class.getName()); + + //TODO use LoggerMetric instead + private static Logger healthCheckLogger = Logger.getLogger("elasticsearch.healthcheck"); ///// HealthCheck///////// private static final String ES_HEALTH_CHECK_STR = "elasticsearchHealthCheck"; @@ -67,7 +65,7 @@ public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO { private class HealthCheckScheduledTask implements Runnable { @Override public void run() { - healthCheckLogger.trace("Executing ELASTICSEARCH Health Check Task - Start"); + log.trace("Executing ELASTICSEARCH Health Check Task - Start"); HealthCheckStatus healthStatus = null; try { @@ -77,7 +75,7 @@ public class ESCatalogDAO extends ESGenericSearchDAO implements ICatalogDAO { getEsClient().getServerHost(), getEsClient().getServerPort(), e.getMessage(), e); healthStatus = HealthCheckStatus.DOWN; } - healthCheckLogger.trace("Executed ELASTICSEARCH Health Check Task - Status = {}", healthStatus); + log.trace("Executed ELASTICSEARCH Health Check Task - Status = {}", healthStatus); if (healthStatus != lastHealthState) { log.trace("ELASTICSEARCH Health State Changed to {}. Issuing alarm / recovery alarm...", healthStatus); lastHealthState = healthStatus; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java index 252240b164..dc944d016e 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/ESTimeBasedDao.java @@ -20,13 +20,8 @@ package org.openecomp.sdc.be.dao.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.Resource; - +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import org.elasticsearch.action.index.IndexResponse; @@ -41,16 +36,18 @@ import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.dao.es.ElasticSearchClient; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.datastructure.ESTimeBasedEvent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public abstract class ESTimeBasedDao { private static final String SCORE_SCRIPT = "_score * ((doc.containsKey('alienScore') && !doc['alienScore'].empty) ? doc['alienScore'].value : 1)"; private static final int MAX_SEARCH_SIZE = 1000; - private static Logger log = LoggerFactory.getLogger(ESTimeBasedDao.class.getName()); + private static Logger log = Logger.getLogger(ESTimeBasedDao.class.getName()); private Gson gson; @@ -71,7 +68,7 @@ public abstract class ESTimeBasedDao { @Resource(name = "elasticsearch-client") private ElasticSearchClient esClient; - protected final Map<String, Class<?>> typesToClasses = new HashMap<String, Class<?>>(); + protected final Map<String, Class<?>> typesToClasses = new HashMap<>(); public abstract String getIndexPrefix(); @@ -99,7 +96,7 @@ public abstract class ESTimeBasedDao { res = ActionStatus.GENERAL_ERROR; } } catch (Exception e) { - log.error("Couldn't serialize object of type {} | error:", typeName, e); + log.error("Couldn't serialize object of type {}", typeName, e.getMessage()); res = ActionStatus.GENERAL_ERROR; } return res; @@ -137,7 +134,7 @@ public abstract class ESTimeBasedDao { } private void setIndexPrefix2CreationPeriod() { - indexPrefix2CreationPeriod = new HashMap<String, String>(); + indexPrefix2CreationPeriod = new HashMap<>(); List<IndicesTimeFrequencyEntry> indicesTimeFrequencyEntries = configurationManager.getConfiguration() .getElasticSearch().getIndicesTimeFrequency(); for (IndicesTimeFrequencyEntry entry : indicesTimeFrequencyEntries) { @@ -199,7 +196,7 @@ public abstract class ESTimeBasedDao { if (!somethingFound(response)) { return null; } else { - List<T> hits = new ArrayList<T>(); + List<T> hits = new ArrayList<>(); for (int i = 0; i < response.getHits().getHits().length; i++) { String hit = response.getHits().getAt(i).sourceAsString(); @@ -226,7 +223,7 @@ public abstract class ESTimeBasedDao { if (!somethingFound(response)) { return null; } else { - List<ESTimeBasedEvent> hits = new ArrayList<ESTimeBasedEvent>(); + List<ESTimeBasedEvent> hits = new ArrayList<>(); for (int i = 0; i < response.getHits().getHits().length; i++) { String hit = response.getHits().getAt(i).sourceAsString(); @@ -247,7 +244,7 @@ public abstract class ESTimeBasedDao { throws JSONException { List<ESTimeBasedEvent> results = doCustomFindForEvent(typeName, query, sortBuilder, MAX_SEARCH_SIZE); if (results == null) { - results = new ArrayList<ESTimeBasedEvent>(); + results = new ArrayList<>(); } return results; } diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java index 04d985bc83..d6502b71c8 100644 --- a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/EsHealthCheckDao.java @@ -20,19 +20,18 @@ package org.openecomp.sdc.be.dao.impl; -import javax.annotation.Resource; - import org.openecomp.sdc.be.dao.api.IEsHealthCheckDao; import org.openecomp.sdc.be.dao.es.ElasticSearchClient; import org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.common.log.wrappers.Logger; import org.springframework.stereotype.Component; +import javax.annotation.Resource; + @Component("esHealthCheckDao") public class EsHealthCheckDao implements IEsHealthCheckDao { - private static Logger logger = LoggerFactory.getLogger(EsHealthCheckDao.class.getName()); + private static Logger logger = Logger.getLogger(EsHealthCheckDao.class.getName()); @Resource(name = "elasticsearch-client") private ElasticSearchClient esClient; diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java new file mode 100644 index 0000000000..7a5f873549 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jElementDAO.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.api.IElementDAO; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary; +import org.openecomp.sdc.be.dao.neo4j.Neo4jClient; +import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import java.util.List; + +//@Component("elements-dao") +public class Neo4jElementDAO implements IElementDAO { + + // @Resource + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jElementDAO.class.getName()); + + @Override + public Either<List<GraphElement>, ActionStatus> getAllCategories() { + MatchFilter filter = new MatchFilter(); + Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.ResourceCategory.getName(), filter); + if (status.isRight()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + List<GraphElement> value = status.left().value(); + if (value == null || value.isEmpty()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + return Either.left(value); + } + } + } + + @Override + public Either<List<GraphElement>, ActionStatus> getAllTags() { + MatchFilter filter = new MatchFilter(); + Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.Tag.getName(), filter); + if (status.isRight()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + List<GraphElement> value = status.left().value(); + if (value == null) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + return Either.left(value); + } + } + } + + @Override + public Either<GraphElement, ActionStatus> getCategory(String name) { + MatchFilter filter = new MatchFilter(); + filter.addToMatch(GraphPropertiesDictionary.NAME.getProperty(), name); + Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.ResourceCategory.getName(), filter); + if (status.isRight()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + List<GraphElement> value = status.left().value(); + if (value == null) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + return Either.left(value.get(0)); + } + } + + } + + /** + * FOR TEST ONLY + * + * @param neo4jClient + */ + public void setNeo4jClient(Neo4jClient neo4jClient) { + this.neo4jClient = neo4jClient; + } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java new file mode 100644 index 0000000000..8c3c5795a9 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jPropertyDAO.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.impl; + +import org.openecomp.sdc.be.dao.api.BasicDao; +import org.openecomp.sdc.be.dao.api.IPropertyDAO; +import org.openecomp.sdc.be.dao.neo4j.Neo4jClient; +import org.openecomp.sdc.be.dao.neo4j.Neo4jGraphBatchBuilder; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.annotation.PostConstruct; + +//@Component("neo4j-property-dao") +public class Neo4jPropertyDAO extends BasicDao implements IPropertyDAO { + + // @Resource + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jPropertyDAO.class.getName()); + + Neo4jGraphBatchBuilder graphBatchBuilder = new Neo4jGraphBatchBuilder(); + + public Neo4jPropertyDAO() { + + } + + @PostConstruct + public void init() { + setNeo4jClient(neo4jClient); + } +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java new file mode 100644 index 0000000000..9cf75f15e3 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jResourceDAO.java @@ -0,0 +1,217 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.BasicDao; +import org.openecomp.sdc.be.dao.api.IResourceDAO; +import org.openecomp.sdc.be.dao.graph.datatype.*; +import org.openecomp.sdc.be.dao.neo4j.*; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.dao.neo4j.filters.RecursiveFilter; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.ResourceMetadataData; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.Map; + +//@Component("neo4j-resource-dao") +public class Neo4jResourceDAO extends BasicDao implements IResourceDAO { + + // @Resource + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jResourceDAO.class.getName()); + + Neo4jGraphBatchBuilder graphBatchBuilder = new Neo4jGraphBatchBuilder(); + + public Neo4jResourceDAO() { + + } + + @PostConstruct + public void init() { + super.setNeo4jClient(neo4jClient); + } + + private String findResourceDataIdFromNodes(List<GraphNode> nodes) { + + if (nodes != null) { + + for (GraphNode neo4jNode : nodes) { + String label = neo4jNode.getLabel(); + if (label.equals(NodeTypeEnum.Resource.getName())) { + return neo4jNode.getUniqueId().toString(); + } + } + } + + return null; + } + + private GraphRelation addStateRelation(RelationEndPoint from, RelationEndPoint to, GraphEdgeLabels edgeLabel, + String value) { + + GraphRelation relationState = new GraphRelation(); + relationState.setFrom(from); + relationState.setTo(to); + relationState.setType(edgeLabel.name()); + relationState.setAction(ActionEnum.Create); + return relationState; + } + + // private ActionStatus convertNeo4jOperationStatusToActionStatus( + // Neo4jOperationStatus value) { + // + // if (value == null) { + // return ActionStatus.GENERAL_ERROR; + // } + // + // switch (value) { + // case NOT_FOUND: + // return ActionStatus.RESOURCE_NOT_FOUND; + // case ERROR: + // return ActionStatus.GENERAL_ERROR; + // case NOT_SUPPORTED: + // return ActionStatus.INVALID_CONTENT; + // case WRONG_INPUT: + // return ActionStatus.INVALID_CONTENT; + // case OK: + // return ActionStatus.OK; + // default: + // return ActionStatus.GENERAL_ERROR; + // } + // + // } + + @Override + public Either<ResourceMetadataData, Neo4jOperationStatus> getResourceData(String id) { + + MatchFilter filter = new MatchFilter(); + filter.addToMatch(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), id); + Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.Resource.getName(), filter); + + if (status.isRight()) { + return Either.right(status.right().value()); + } else { + List<GraphElement> value = status.left().value(); + if (value == null || value.isEmpty()) { + return Either.right(Neo4jOperationStatus.NOT_FOUND); + } else { + return Either.left((ResourceMetadataData) value.get(0)); + } + } + } + + @Override + public Either<Integer, Neo4jOperationStatus> getNumberOfResourcesByName(String name) { + + MatchFilter filter = new MatchFilter(); + filter.addToMatch(GraphPropertiesDictionary.NAME.getProperty(), name); + Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.Resource.getName(), filter); + + if (status.isRight() || (status.left().value() == null)) { + return Either.right(Neo4jOperationStatus.GENERAL_ERROR); + } else { + List<GraphElement> value = status.left().value(); + return Either.left(value.size()); + } + } + + @Override + public void setNeo4jClient(Neo4jClient client) { + this.neo4jClient = client; + super.setNeo4jClient(client); + } + + @Override + public Either<List<ResourceMetadataData>, Neo4jOperationStatus> getAllResourcesData( + Map<String, Object> propertiesToMatch) { + + RecursiveFilter filter = new RecursiveFilter(NodeTypeEnum.Resource); + // filter.addRelationType("typeof").addRelationType("belong").setProperties(propertiesToMatch); + + Either<List<List<GraphElement>>, Neo4jOperationStatus> ret = neo4jClient.executeGet(filter); + if (ret.isRight()) { + return Either.right(ret.right().value()); + } + List<List<GraphElement>> listOfListOfNeo4jElement = ret.left().value(); + + for (List<GraphElement> row : listOfListOfNeo4jElement) { + + for (GraphElement elem : row) { + + } + } + return Either.right(null); + + /* + * MatchFilter filter = new MatchFilter(); if(propertiesToMatch != + * null){ for (Entry<String,Object> propertie : + * propertiesToMatch.entrySet()){ filter.addToMatch(propertie.getKey(), + * propertie.getValue()); } } Either<List<GraphElement>, + * Neo4jOperationStatus> status = + * neo4jClient.getByFilter(GraphElementTypeEnum.Node, + * NodeTypeEnum.Resource.getName(), filter); if (status.isRight()) { + * return Either.right(status.right().value()); } else { + * List<GraphElement> value = status.left().value(); if (value == null + * || value.isEmpty()) { return + * Either.right(Neo4jOperationStatus.NOT_FOUND); } else { + * List<ResourceData> result=new ArrayList<>(); for(GraphElement element + * : value ){ result.add((ResourceData)element); } return + * Either.left(result); } } + */ + } + + // @Override + // public ActionStatus updateUserData(UserData userData) { + // UpdateFilter filter = new UpdateFilter(); + // filter.addToMatch("userId", userData.getUserId()); + // filter.setToUpdate(userData.toMap()); + // Neo4jOperationStatus status = + // neo4jClient.updateElement(Neo4JElementTypeEnum.Node, + // NodeTypeEnum.User.getName(), filter); + // if (status.equals(Neo4jOperationStatus.OK)) { + // return ActionStatus.OK; + // } else { + // return ActionStatus.GENERAL_ERROR; + // } + // } + // + // @Override + // public ActionStatus deleteUserData(String id) { + // MatchFilter filter = new MatchFilter(); + // filter.addToMatch("userId", id); + // Neo4jOperationStatus status = + // neo4jClient.deleteElement(Neo4JElementTypeEnum.Node, + // NodeTypeEnum.User.getName(), filter); + // if (status.equals(Neo4jOperationStatus.OK)) { + // return ActionStatus.OK; + // } else { + // return ActionStatus.GENERAL_ERROR; + // } + // } + +} diff --git a/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java new file mode 100644 index 0000000000..448b3e31a1 --- /dev/null +++ b/catalog-dao/src/main/java/org/openecomp/sdc/be/dao/impl/Neo4jUsersDAO.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.dao.impl; + +import fj.data.Either; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.dao.api.IUsersDAO; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElement; +import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum; +import org.openecomp.sdc.be.dao.neo4j.Neo4jClient; +import org.openecomp.sdc.be.dao.neo4j.Neo4jOperationStatus; +import org.openecomp.sdc.be.dao.neo4j.filters.MatchFilter; +import org.openecomp.sdc.be.dao.neo4j.filters.UpdateFilter; +import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum; +import org.openecomp.sdc.be.resources.data.UserData; +import org.openecomp.sdc.common.log.wrappers.Logger; + +import javax.annotation.PostConstruct; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +//@Component("users-dao") +public class Neo4jUsersDAO implements IUsersDAO { + + // @Resource + Neo4jClient neo4jClient; + + private static Logger logger = Logger.getLogger(Neo4jUsersDAO.class.getName()); + + public Neo4jUsersDAO() { + + } + + @PostConstruct + public void init() { + } + + private void createIndexesAndConstraints() { + Either<Map<String, List<String>>, Neo4jOperationStatus> statusInd = neo4jClient + .getIndexes(NodeTypeEnum.User.getName()); + if (statusInd.isRight()) { + logger.error("Failed to get indexes from Neo4j graph"); + throw new RuntimeException("Failed to initialize Neo4jUsersDAO - Failed to get indexes from Neo4j graph"); + } + Map<String, List<String>> indexes = statusInd.left().value(); + if (indexes == null || indexes.isEmpty()) { + logger.info("Define users indexes in Neo4j"); + List<String> propertyNames = new ArrayList<>(); + propertyNames.add("firstName"); + propertyNames.add("lastName"); + propertyNames.add("email"); + propertyNames.add("role"); + logger.info("Start create Users indexes in Neo4jGraph"); + Neo4jOperationStatus createIndexStatus = neo4jClient.createIndex(NodeTypeEnum.User.getName(), + propertyNames); + if (createIndexStatus.equals(Neo4jOperationStatus.OK)) { + logger.info("Users indexes created in Neo4j"); + List<String> propertyUnique = new ArrayList<>(); + propertyUnique.add("userId"); + + logger.info("Start create Users constraints in Neo4jGraph"); + Neo4jOperationStatus createUniquenessStatus = neo4jClient + .createUniquenessConstraints(NodeTypeEnum.User.getName(), propertyUnique); + if (createUniquenessStatus.equals(Neo4jOperationStatus.OK)) { + logger.info("Users constraints creatyed in Neo4j"); + } else { + logger.error("Failed to create constraints in Neo4j graph [{}]", createUniquenessStatus); + throw new RuntimeException( + "Failed to initialize Neo4jUsersDAO - Failed to create constraints in Neo4j graph"); + } + } else { + logger.error("Failed to create indexes in Neo4j graph [{}]", createIndexStatus); + throw new RuntimeException( + "Failed to initialize Neo4jUsersDAO - Failed to create indexes in Neo4j graph"); + } + } else { + logger.info("Users indexes already defined in Neo4j"); + } + } + + @Override + public Either<UserData, ActionStatus> getUserData(String id) { + MatchFilter filter = new MatchFilter(); + filter.addToMatch("userId", id); + Either<List<GraphElement>, Neo4jOperationStatus> status = neo4jClient.getByFilter(GraphElementTypeEnum.Node, + NodeTypeEnum.User.getName(), filter); + if (status.isRight()) { + return Either.right(ActionStatus.GENERAL_ERROR); + } else { + List<GraphElement> value = status.left().value(); + if (value == null || value.isEmpty()) { + return Either.right(ActionStatus.USER_NOT_FOUND); + } else { + return Either.left((UserData) value.get(0)); + } + } + } + + @Override + public ActionStatus saveUserData(UserData userData) { + Neo4jOperationStatus status = neo4jClient.createElement(userData); + if (status.equals(Neo4jOperationStatus.OK)) { + return ActionStatus.OK; + } else { + return ActionStatus.GENERAL_ERROR; + } + } + + @Override + public ActionStatus updateUserData(UserData userData) { + UpdateFilter filter = new UpdateFilter(); + filter.addToMatch("userId", userData.getUserId()); + filter.setToUpdate(userData.toGraphMap()); + Neo4jOperationStatus status = neo4jClient.updateElement(GraphElementTypeEnum.Node, NodeTypeEnum.User.getName(), + filter); + if (status.equals(Neo4jOperationStatus.OK)) { + return ActionStatus.OK; + } else { + return ActionStatus.GENERAL_ERROR; + } + } + + @Override + public ActionStatus deleteUserData(String id) { + MatchFilter filter = new MatchFilter(); + filter.addToMatch("userId", id); + Neo4jOperationStatus status = neo4jClient.deleteElement(GraphElementTypeEnum.Node, NodeTypeEnum.User.getName(), + filter); + if (status.equals(Neo4jOperationStatus.OK)) { + return ActionStatus.OK; + } else { + return ActionStatus.GENERAL_ERROR; + } + } + + public Neo4jClient getNeo4jClient() { + return neo4jClient; + } + + public void setNeo4jClient(Neo4jClient neo4jClient) { + this.neo4jClient = neo4jClient; + } + +} |