diff options
author | 2017-10-10 11:09:06 -0400 | |
---|---|---|
committer | 2017-10-10 11:10:17 -0400 | |
commit | db2e2b074eeea255a798a684313453d260b4d682 (patch) | |
tree | 4d6f483d22c238617789443f156bd25bdd1c28fb /src/main/java/org/onap | |
parent | 6ec1f2e784928e9391381608e40df77432c4255d (diff) |
Increase junit coverage
Issue-ID: AAI-429
Change-Id: Ifde57eee0857509ae223a6399cee8601af58ec39
Signed-off-by: Arul.Nambi <arul.nambi@amdocs.com>
Diffstat (limited to 'src/main/java/org/onap')
6 files changed, 76 insertions, 1244 deletions
diff --git a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/config/ElasticSearchConfig.java b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/config/ElasticSearchConfig.java index 863fa4b..2fe6bb6 100644 --- a/src/main/java/org/onap/aai/sparky/dal/elasticsearch/config/ElasticSearchConfig.java +++ b/src/main/java/org/onap/aai/sparky/dal/elasticsearch/config/ElasticSearchConfig.java @@ -68,8 +68,6 @@ public class ElasticSearchConfig { private String auditIndexName; - private String topographicalSearchIndex; - private String entityCountHistoryIndex; private String autosuggestIndexname; @@ -185,8 +183,6 @@ public class ElasticSearchConfig { mappingsFileName = props.getProperty("elasticsearch.mappingsFileName"); settingsFileName = props.getProperty("elasticsearch.settingsFileName"); auditIndexName = props.getProperty("elasticsearch.auditIndexName", AUDIT_INDEX_NAME_DEFAULT); - topographicalSearchIndex = - props.getProperty("elasticsearch.topographicalIndexName", TOPOGRAPHICAL_INDEX_NAME_DEFAULT); entityCountHistoryIndex = props.getProperty("elasticsearch.entityCountHistoryIndexName", ENTITY_COUNT_HISTORY_INDEX_NAME_DEFAULT); entityCountHistoryMappingsFileName = @@ -290,14 +286,6 @@ public class ElasticSearchConfig { this.auditIndexName = auditIndexName; } - public String getTopographicalSearchIndex() { - return topographicalSearchIndex; - } - - public void setTopographicalSearchIndex(String topographicalSearchIndex) { - this.topographicalSearchIndex = topographicalSearchIndex; - } - public String getEntityCountHistoryIndex() { return entityCountHistoryIndex; } @@ -529,7 +517,7 @@ public class ElasticSearchConfig { + ", clusterName=" + clusterName + ", mappingsFileName=" + mappingsFileName + ", settingsFileName=" + settingsFileName + ", syncAdapterMaxConcurrentWorkers=" + syncAdapterMaxConcurrentWorkers + ", auditIndexName=" + auditIndexName - + ", topographicalSearchIndex=" + topographicalSearchIndex + ", entityCountHistoryIndex=" + + ", entityCountHistoryIndex=" + entityCountHistoryIndex + ", autosuggestIndexname=" + autosuggestIndexname + ", entityCountHistoryMappingsFileName=" + entityCountHistoryMappingsFileName + ", autoSuggestSettingsFileName=" + autoSuggestSettingsFileName diff --git a/src/main/java/org/onap/aai/sparky/inventory/servlet/GeoVisualizationServlet.java b/src/main/java/org/onap/aai/sparky/inventory/servlet/GeoVisualizationServlet.java deleted file mode 100644 index b0a0670..0000000 --- a/src/main/java/org/onap/aai/sparky/inventory/servlet/GeoVisualizationServlet.java +++ /dev/null @@ -1,220 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.sparky.inventory.servlet; - -import org.onap.aai.cl.mdc.MdcContext; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.ByteBuffer; -import java.security.SecureRandom; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.onap.aai.cl.api.Logger; -import org.onap.aai.cl.eelf.LoggerFactory; -import org.json.JSONArray; -import org.json.JSONObject; -import org.onap.aai.sparky.dal.elasticsearch.SearchAdapter; -import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig; -import org.onap.aai.sparky.dal.rest.OperationResult; -import org.onap.aai.sparky.dal.rest.RestClientBuilder; -import org.onap.aai.sparky.logging.AaiUiMsgs; -import org.onap.aai.sparky.util.NodeUtils; -import org.onap.aai.sparky.util.ServletUtils; - -/** - * The Class GeoVisualizationServlet. - */ -public class GeoVisualizationServlet extends HttpServlet { - - private static final Logger LOG = - LoggerFactory.getInstance().getLogger(GeoVisualizationServlet.class); - - private static final long serialVersionUID = 1L; - - private SearchAdapter search = null; - private ElasticSearchConfig elasticConfig = null; - private ObjectMapper mapper; - - private static final String SEARCH_STRING = "_search"; - - private static final String SEARCH_PARAMETER = - "?filter_path=hits.hits._source&_source=location&size=5000&q=entityType:"; - - /** - * Instantiates a new geo visualization servlet. - * - * @throws ServletException the servlet exception - */ - public GeoVisualizationServlet() throws ServletException { - init(); - } - - /* (non-Javadoc) - * @see javax.servlet.GenericServlet#init() - */ - @Override - public void init() throws ServletException { - super.init(); - try { - if (elasticConfig == null) { - elasticConfig = ElasticSearchConfig.getConfig(); - } - if (search == null) { - search = new SearchAdapter(); - } - this.mapper = new ObjectMapper(); - } catch (Exception exc) { - new ServletException( - "Caught an exception while getting an instance of servlet configuration.", exc); - } - } - - public void setSearch(SearchAdapter search) { - this.search = search; - } - - public void setElasticConfig(ElasticSearchConfig elasticConfig) { - this.elasticConfig = elasticConfig; - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - String txnID = request.getHeader("X-TransactionId"); - if (txnID == null){ - txnID = NodeUtils.getRandomTxnId(); - } - - String partnerName = request.getHeader("X-FromAppId"); - if ( partnerName == null) - partnerName = "Browser"; - - MdcContext.initialize(txnID, "AAI-UI", "", partnerName, - request.getRemoteAddr()); - - OperationResult operationResult = null; - try { - operationResult = getGeoVisualizationResults(response, request.getParameter("entity")); - } catch (Exception exc) { - LOG.error(AaiUiMsgs.ERROR_PROCESSING_REQUEST, exc); - } - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException { - - } - - /** - * Gets the geo visualization results. - * - * @param response the response - * @param entityType the entity type - * @return the geo visualization results - * @throws Exception the exception - */ - protected OperationResult getGeoVisualizationResults(HttpServletResponse response, - String entityType) throws Exception { - OperationResult operationResult = new OperationResult(); - - String parameters = SEARCH_PARAMETER + entityType; - String requestString = String.format("/%s/%s/%s", elasticConfig.getTopographicalSearchIndex(), - SEARCH_STRING, parameters); - - try { - final String fullUrlStr = ServletUtils.getFullUrl(elasticConfig, requestString); - OperationResult opResult = ServletUtils.executeGetQuery(LOG, search, response, fullUrlStr); - - JSONObject finalOutputJson = formatOutput(opResult.getResult()); - - if (finalOutputJson != null) { - response.setContentType("application/json"); - PrintWriter out = response.getWriter(); - out.println(finalOutputJson); - out.close(); - } - - } catch (JsonProcessingException exc) { - ServletUtils.handleSearchServletErrors(LOG, "Unable to map JSONpayload", exc, response); - } - - return operationResult; - } - - /** - * Format output. - * - * @param results the results - * @return the JSON object - */ - private JSONObject formatOutput(String results) { - JsonNode resultNode = null; - JSONObject finalResult = new JSONObject(); - JSONArray entitiesArr = new JSONArray(); - - try { - resultNode = mapper.readTree(results); - - final JsonNode hitsNode = resultNode.get("hits").get("hits"); - if (hitsNode.isArray()) { - - for (final JsonNode arrayNode : hitsNode) { - JsonNode sourceNode = arrayNode.get("_source"); - if (sourceNode.get("location") != null) { - JsonNode locationNode = sourceNode.get("location"); - if (NodeUtils.isNumeric(locationNode.get("lon").asText()) - && NodeUtils.isNumeric(locationNode.get("lat").asText())) { - JSONObject location = new JSONObject(); - location.put("longitude", locationNode.get("lon").asText()); - location.put("latitude", locationNode.get("lat").asText()); - - entitiesArr.put(location); - } - - } - } - } - finalResult.put("plotPoints", entitiesArr); - - } catch (IOException exc) { - LOG.warn(AaiUiMsgs.ERROR_BUILDING_SEARCH_RESPONSE, exc.getLocalizedMessage()); - } - - return finalResult; - } -} diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/GeoSynchronizer.java b/src/main/java/org/onap/aai/sparky/synchronizer/GeoSynchronizer.java deleted file mode 100644 index 0f3926d..0000000 --- a/src/main/java/org/onap/aai/sparky/synchronizer/GeoSynchronizer.java +++ /dev/null @@ -1,466 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.sparky.synchronizer; - -import static java.util.concurrent.CompletableFuture.supplyAsync; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Deque; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentLinkedDeque; -import java.util.function.Supplier; - -import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor; -import org.onap.aai.sparky.dal.NetworkTransaction; -import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig; -import org.onap.aai.sparky.dal.rest.HttpMethod; -import org.onap.aai.sparky.dal.rest.OperationResult; -import org.onap.aai.sparky.inventory.entity.GeoIndexDocument; -import org.onap.aai.sparky.logging.AaiUiMsgs; -import org.onap.aai.sparky.synchronizer.entity.SelfLinkDescriptor; -import org.onap.aai.sparky.synchronizer.enumeration.OperationState; -import org.onap.aai.sparky.synchronizer.enumeration.SynchronizerState; -import org.onap.aai.sparky.synchronizer.task.PerformActiveInventoryRetrieval; -import org.onap.aai.sparky.synchronizer.task.StoreDocumentTask; -import org.onap.aai.sparky.util.NodeUtils; -import org.onap.aai.cl.api.Logger; -import org.onap.aai.cl.eelf.LoggerFactory; -import org.onap.aai.cl.mdc.MdcContext; -import org.slf4j.MDC; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; - - -/** - * The Class GeoSynchronizer. - */ -public class GeoSynchronizer extends AbstractEntitySynchronizer implements IndexSynchronizer { - - private static final Logger LOG = LoggerFactory.getInstance().getLogger(GeoSynchronizer.class); - - private boolean allWorkEnumerated; - private Deque<SelfLinkDescriptor> selflinks; - - private ElasticSearchConfig elasticConfig = null; - private Map<String, OxmEntityDescriptor> geoDescriptorMap = null; - - /** - * Instantiates a new geo synchronizer. - * - * @param indexName the index name - * @throws Exception the exception - */ - public GeoSynchronizer(String indexName) throws Exception { - - super(LOG, "GEO", 2, 5, 5, indexName); - this.allWorkEnumerated = false; - this.selflinks = new ConcurrentLinkedDeque<SelfLinkDescriptor>(); - this.synchronizerName = "Geo Synchronizer"; - this.geoDescriptorMap = oxmModelLoader.getGeoEntityDescriptors(); - this.aaiEntityStats.initializeCountersFromOxmEntityDescriptors(geoDescriptorMap); - this.esEntityStats.initializeCountersFromOxmEntityDescriptors(geoDescriptorMap); - this.syncDurationInMs = -1; - } - - - /* (non-Javadoc) - * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#doSync() - */ - @Override - public OperationState doSync() { - resetCounters(); - allWorkEnumerated = false; - syncStartedTimeStampInMs = System.currentTimeMillis(); - String txnID = NodeUtils.getRandomTxnId(); - MdcContext.initialize(txnID, "GeoSynchronizer", "", "Sync", ""); - - collectAllTheWork(); - return OperationState.OK; - } - - - /** - * Collect all the work. - * - * @return the operation state - */ - public OperationState collectAllTheWork() { - final Map<String,String> contextMap = MDC.getCopyOfContextMap(); - if (elasticConfig == null) { - try { - elasticConfig = ElasticSearchConfig.getConfig(); - } catch (Exception exc) { - LOG.error(AaiUiMsgs.CONFIGURATION_ERROR, "Search"); - } - } - - if (geoDescriptorMap.isEmpty()) { - setShouldSkipSync(true); - LOG.error(AaiUiMsgs.OXM_FAILED_RETRIEVAL, "geo entities"); - return OperationState.ERROR; - } - - Collection<String> syncTypes = geoDescriptorMap.keySet(); - - try { - - /* - * launch a parallel async thread to process the documents for each entity-type (to max the of - * the configured executor anyway) - */ - - aaiWorkOnHand.set(syncTypes.size()); - - for (String key : syncTypes) { - - supplyAsync(new Supplier<Void>() { - - @Override - public Void get() { - MDC.setContextMap(contextMap); - OperationResult typeLinksResult = null; - try { - typeLinksResult = aaiDataProvider.getSelfLinksByEntityType(key); - aaiWorkOnHand.decrementAndGet(); - processEntityTypeSelfLinks(typeLinksResult); - } catch (Exception exc) { - LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, exc); - } - - return null; - } - - }, aaiExecutor).whenComplete((result, error) -> { - - if (error != null) { - LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage()); - } - }); - - } - - while (aaiWorkOnHand.get() != 0) { - - if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.WAIT_FOR_ALL_SELFLINKS_TO_BE_COLLECTED); - } - - Thread.sleep(1000); - } - - aaiWorkOnHand.set(selflinks.size()); - allWorkEnumerated = true; - syncEntityTypes(); - - } catch (Exception exc) { - LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, exc); - } - return OperationState.OK; - } - - /** - * Sync entity types. - */ - private void syncEntityTypes() { - - while (selflinks.peek() != null) { - - SelfLinkDescriptor linkDescriptor = selflinks.poll(); - aaiWorkOnHand.decrementAndGet(); - - OxmEntityDescriptor descriptor = null; - - if (linkDescriptor.getSelfLink() != null && linkDescriptor.getEntityType() != null) { - - descriptor = oxmModelLoader.getEntityDescriptor(linkDescriptor.getEntityType()); - - if (descriptor == null) { - LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, linkDescriptor.getEntityType()); - // go to next element in iterator - continue; - } - - NetworkTransaction txn = new NetworkTransaction(); - txn.setDescriptor(descriptor); - txn.setLink(linkDescriptor.getSelfLink()); - txn.setOperationType(HttpMethod.GET); - txn.setEntityType(linkDescriptor.getEntityType()); - - aaiWorkOnHand.incrementAndGet(); - - supplyAsync(new PerformActiveInventoryRetrieval(txn, aaiDataProvider), aaiExecutor) - .whenComplete((result, error) -> { - - aaiWorkOnHand.decrementAndGet(); - - if (error != null) { - LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, error.getMessage()); - } else { - if (result == null) { - LOG.error(AaiUiMsgs.SELF_LINK_GET_NO_RESPONSE, linkDescriptor.getSelfLink()); - } else { - processEntityTypeSelfLinkResult(result); - } - } - }); - } - } - } - - /** - * Process entity type self links. - * - * @param operationResult the operation result - */ - private void processEntityTypeSelfLinks(OperationResult operationResult) { - - JsonNode rootNode = null; - - final String jsonResult = operationResult.getResult(); - - if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) { - - try { - rootNode = mapper.readTree(jsonResult); - } catch (IOException exc) { - LOG.error(AaiUiMsgs.ERROR_GENERIC, exc); - return; - } - - JsonNode resultData = rootNode.get("result-data"); - ArrayNode resultDataArrayNode = null; - - if (resultData.isArray()) { - resultDataArrayNode = (ArrayNode) resultData; - - Iterator<JsonNode> elementIterator = resultDataArrayNode.elements(); - JsonNode element = null; - - while (elementIterator.hasNext()) { - element = elementIterator.next(); - - final String resourceType = NodeUtils.getNodeFieldAsText(element, "resource-type"); - final String resourceLink = NodeUtils.getNodeFieldAsText(element, "resource-link"); - - if (resourceType != null && resourceLink != null) { - - if (geoDescriptorMap.containsKey(resourceType)) { - selflinks.add(new SelfLinkDescriptor(resourceLink + "?nodes-only", resourceType)); - } else { - LOG.error(AaiUiMsgs.MISSING_ENTITY_DESCRIPTOR, resourceType); - // go to next element in iterator - continue; - } - - } - } - } - } - - } - - /** - * Process entity type self link result. - * - * @param txn the txn - */ - private void processEntityTypeSelfLinkResult(NetworkTransaction txn) { - - updateActiveInventoryCounters(txn); - - if (!txn.getOperationResult().wasSuccessful()) { - return; - } - - try { - if (!(txn.getDescriptor().getGeoLatName().isEmpty() - && txn.getDescriptor().getGeoLongName().isEmpty())) { - - GeoIndexDocument geoDoc = new GeoIndexDocument(oxmModelLoader); - - final String jsonResult = txn.getOperationResult().getResult(); - - if (jsonResult != null && jsonResult.length() > 0) { - - populateGeoDocument(geoDoc, jsonResult, txn.getDescriptor(), txn.getLink()); - - if (!geoDoc.isValidGeoDocument()) { - - LOG.info(AaiUiMsgs.GEO_SYNC_IGNORING_ENTITY, geoDoc.getEntityType(), geoDoc.toString()); - - } else { - - String link = null; - try { - link = getElasticFullUrl("/" + geoDoc.getId(), getIndexName(), "default"); - } catch (Exception exc) { - LOG.error(AaiUiMsgs.ES_FAILED_TO_CONSTRUCT_URI, exc); - } - - if (link != null) { - - NetworkTransaction n2 = new NetworkTransaction(); - n2.setLink(link); - n2.setEntityType(txn.getEntityType()); - n2.setDescriptor(txn.getDescriptor()); - n2.setOperationType(HttpMethod.PUT); - - esWorkOnHand.incrementAndGet(); - - supplyAsync(new StoreDocumentTask(geoDoc, n2, esDataProvider), esExecutor) - .whenComplete((result, error) -> { - - esWorkOnHand.decrementAndGet(); - - if (error != null) { - LOG.error(AaiUiMsgs.ES_STORE_FAILURE, error.getMessage()); - } else { - updateElasticSearchCounters(result); - processStoreDocumentResult(result); - } - }); - } - } - } - } - } catch (JsonProcessingException exc) { - LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, exc); - } catch (IOException exc) { - LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, exc); - } - - return; - } - - - /** - * Process store document result. - * - * @param txn the txn - */ - private void processStoreDocumentResult(NetworkTransaction txn) { - - OperationResult or = txn.getOperationResult(); - - if (!or.wasSuccessful()) { - LOG.error(AaiUiMsgs.ES_STORE_FAILURE, or.toString()); - /* - * if(or.getResultCode() != 404 || (or.getResultCode() == 404 && - * !synchronizerConfig.isResourceNotFoundErrorsSupressed())) { logger.error( - * "Skipping failed resource = " + "link" + " RC=[" + or.getResultCode() + "]. Message: " + - * or.getResult()); } - */ - - } - - } - - - @Override - public SynchronizerState getState() { - - if (!isSyncDone()) { - return SynchronizerState.PERFORMING_SYNCHRONIZATION; - } - - return SynchronizerState.IDLE; - - } - - /* (non-Javadoc) - * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean) - */ - @Override - public String getStatReport(boolean showFinalReport) { - syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; - return this.getStatReport(syncDurationInMs, showFinalReport); - } - - /* (non-Javadoc) - * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#shutdown() - */ - @Override - public void shutdown() { - this.shutdownExecutors(); - } - - /** - * Populate geo document. - * - * @param doc the doc - * @param result the result - * @param resultDescriptor the result descriptor - * @param entityLink the entity link - * @throws JsonProcessingException the json processing exception - * @throws IOException Signals that an I/O exception has occurred. - */ - protected void populateGeoDocument(GeoIndexDocument doc, String result, - OxmEntityDescriptor resultDescriptor, String entityLink) - throws JsonProcessingException, IOException { - - doc.setSelfLink(entityLink); - doc.setEntityType(resultDescriptor.getEntityName()); - - JsonNode entityNode = mapper.readTree(result); - - List<String> primaryKeyValues = new ArrayList<String>(); - String pkeyValue = null; - - for (String keyName : resultDescriptor.getPrimaryKeyAttributeName()) { - pkeyValue = NodeUtils.getNodeFieldAsText(entityNode, keyName); - if (pkeyValue != null) { - primaryKeyValues.add(pkeyValue); - } else { - LOG.warn(AaiUiMsgs.ES_PKEYVALUE_NULL, resultDescriptor.getEntityName()); - } - } - - final String primaryCompositeKeyValue = NodeUtils.concatArray(primaryKeyValues, "/"); - doc.setEntityPrimaryKeyValue(primaryCompositeKeyValue); - String geoLatKey = resultDescriptor.getGeoLatName(); - String geoLongKey = resultDescriptor.getGeoLongName(); - - doc.setLatitude(NodeUtils.getNodeFieldAsText(entityNode, geoLatKey)); - doc.setLongitude(NodeUtils.getNodeFieldAsText(entityNode, geoLongKey)); - doc.deriveFields(); - - } - - @Override - protected boolean isSyncDone() { - int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get(); - - if (totalWorkOnHand > 0 || !allWorkEnumerated) { - return false; - } - - return true; - } - -} diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/HistoricalEntitySummarizer.java b/src/main/java/org/onap/aai/sparky/synchronizer/HistoricalEntitySummarizer.java deleted file mode 100644 index 714e016..0000000 --- a/src/main/java/org/onap/aai/sparky/synchronizer/HistoricalEntitySummarizer.java +++ /dev/null @@ -1,368 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. - * Copyright © 2017 Amdocs - * ================================================================================ - * 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.sparky.synchronizer; - -import static java.util.concurrent.CompletableFuture.supplyAsync; - -import java.io.IOException; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; -import java.util.Collection; -import java.util.EnumSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; - -import javax.json.Json; - -import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor; -import org.onap.aai.sparky.dal.rest.HttpMethod; -import org.onap.aai.sparky.dal.rest.OperationResult; -import org.onap.aai.sparky.logging.AaiUiMsgs; -import org.onap.aai.sparky.synchronizer.enumeration.OperationState; -import org.onap.aai.sparky.synchronizer.enumeration.SynchronizerState; -import org.onap.aai.sparky.util.NodeUtils; -import org.onap.aai.cl.api.Logger; -import org.onap.aai.cl.eelf.LoggerFactory; -import org.onap.aai.cl.mdc.MdcContext; -import org.slf4j.MDC; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; - -/** - * The Class HistoricalEntitySummarizer. - */ -public class HistoricalEntitySummarizer extends AbstractEntitySynchronizer - implements IndexSynchronizer { - - private static final Logger LOG = LoggerFactory.getInstance().getLogger(HistoricalEntitySummarizer.class); - private static final String INSERTION_DATE_TIME_FORMAT = "yyyyMMdd'T'HHmmssZ"; - - private boolean allWorkEnumerated; - private ConcurrentHashMap<String, AtomicInteger> entityCounters; - private boolean syncInProgress; - private Map<String, String> contextMap; - - /** - * Instantiates a new historical entity summarizer. - * - * @param indexName the index name - * @throws Exception the exception - */ - public HistoricalEntitySummarizer(String indexName) throws Exception { - super(LOG, "HES", 2, 5, 5, indexName); - - this.allWorkEnumerated = false; - this.entityCounters = new ConcurrentHashMap<String, AtomicInteger>(); - this.synchronizerName = "Historical Entity Summarizer"; - this.enabledStatFlags = EnumSet.of(StatFlag.AAI_REST_STATS, StatFlag.ES_REST_STATS); - this.syncInProgress = false; - this.contextMap = MDC.getCopyOfContextMap(); - this.syncDurationInMs = -1; - } - - /** - * Collect all the work. - * - * @return the operation state - */ - private OperationState collectAllTheWork() { - - Map<String, OxmEntityDescriptor> descriptorMap = - oxmModelLoader.getSearchableEntityDescriptors(); - - if (descriptorMap.isEmpty()) { - LOG.error(AaiUiMsgs.OXM_FAILED_RETRIEVAL, "historical entities"); - - return OperationState.ERROR; - } - - Collection<String> entityTypes = descriptorMap.keySet(); - - AtomicInteger asyncWoH = new AtomicInteger(0); - - asyncWoH.set(entityTypes.size()); - - try { - for (String entityType : entityTypes) { - - supplyAsync(new Supplier<Void>() { - - @Override - public Void get() { - MDC.setContextMap(contextMap); - try { - OperationResult typeLinksResult = - aaiDataProvider.getSelfLinksByEntityType(entityType); - updateActiveInventoryCounters(HttpMethod.GET, entityType, typeLinksResult); - processEntityTypeSelfLinks(entityType, typeLinksResult); - } catch (Exception exc) { - LOG.error(AaiUiMsgs.ERROR_GETTING_DATA_FROM_AAI, exc.getMessage()); - - } - - return null; - } - - }, aaiExecutor).whenComplete((result, error) -> { - - asyncWoH.decrementAndGet(); - - if (error != null) { - LOG.error(AaiUiMsgs.HISTORICAL_COLLECT_ERROR, error.getMessage()); - } - - }); - - } - - - while (asyncWoH.get() > 0) { - - if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, indexName + " summarizer waiting for all the links to be processed."); - } - - Thread.sleep(250); - } - - esWorkOnHand.set(entityCounters.size()); - - // start doing the real work - allWorkEnumerated = true; - - insertEntityTypeCounters(); - - if (LOG.isDebugEnabled()) { - - StringBuilder sb = new StringBuilder(128); - - sb.append("\n\nHistorical Entity Counters:"); - - for (Entry<String, AtomicInteger> entry : entityCounters.entrySet()) { - sb.append("\n").append(entry.getKey()).append(" = ").append(entry.getValue().get()); - } - - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, sb.toString()); - - } - - } catch (Exception exc) { - LOG.error(AaiUiMsgs.HISTORICAL_COLLECT_ERROR, exc.getMessage()); - - - esWorkOnHand.set(0); - allWorkEnumerated = true; - - return OperationState.ERROR; - } - - return OperationState.OK; - - } - - /* (non-Javadoc) - * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#doSync() - */ - @Override - public OperationState doSync() { - String txnID = NodeUtils.getRandomTxnId(); - MdcContext.initialize(txnID, "HistoricalEntitySynchronizer", "", "Sync", ""); - - if (syncInProgress) { - LOG.info(AaiUiMsgs.HISTORICAL_SYNC_PENDING); - return OperationState.PENDING; - } - - clearCache(); - - syncInProgress = true; - this.syncStartedTimeStampInMs = System.currentTimeMillis(); - allWorkEnumerated = false; - - return collectAllTheWork(); - } - - /** - * Process entity type self links. - * - * @param entityType the entity type - * @param operationResult the operation result - */ - private void processEntityTypeSelfLinks(String entityType, OperationResult operationResult) { - - JsonNode rootNode = null; - - final String jsonResult = operationResult.getResult(); - - if (jsonResult != null && jsonResult.length() > 0 && operationResult.wasSuccessful()) { - - try { - rootNode = mapper.readTree(jsonResult); - } catch (IOException exc) { - LOG.error(AaiUiMsgs.JSON_PROCESSING_ERROR, exc.getMessage()); - return; - } - - JsonNode resultData = rootNode.get("result-data"); - ArrayNode resultDataArrayNode = null; - - if (resultData != null && resultData.isArray()) { - resultDataArrayNode = (ArrayNode) resultData; - entityCounters.put(entityType, new AtomicInteger(resultDataArrayNode.size())); - } - } - - } - - /** - * Insert entity type counters. - */ - private void insertEntityTypeCounters() { - - if (esWorkOnHand.get() <= 0) { - return; - } - - SimpleDateFormat dateFormat = new SimpleDateFormat(INSERTION_DATE_TIME_FORMAT); - Timestamp timestamp = new Timestamp(System.currentTimeMillis()); - String currentFormattedTimeStamp = dateFormat.format(timestamp); - - Set<Entry<String, AtomicInteger>> entityCounterEntries = entityCounters.entrySet(); - - for (Entry<String, AtomicInteger> entityCounterEntry : entityCounterEntries) { - - supplyAsync(new Supplier<Void>() { - - @Override - public Void get() { - MDC.setContextMap(contextMap); - String jsonString = Json.createObjectBuilder().add( - "count", entityCounterEntry.getValue().get()) - .add("entityType", entityCounterEntry.getKey()) - .add("timestamp", currentFormattedTimeStamp).build().toString(); - - String link = null; - try { - link = getElasticFullUrl("", indexName); - OperationResult or = esDataProvider.doPost(link, jsonString, "application/json"); - updateElasticSearchCounters(HttpMethod.POST, entityCounterEntry.getKey(), or); - } catch (Exception exc) { - LOG.error(AaiUiMsgs.ES_STORE_FAILURE, exc.getMessage() ); - } - - return null; - } - - }, esExecutor).whenComplete((result, error) -> { - - esWorkOnHand.decrementAndGet(); - - }); - - } - - while (esWorkOnHand.get() > 0) { - - try { - Thread.sleep(500); - } catch (InterruptedException exc) { - LOG.error(AaiUiMsgs.INTERRUPTED, "historical Entities", exc.getMessage()); - } - } - - } - - @Override - public SynchronizerState getState() { - - if (!isSyncDone()) { - return SynchronizerState.PERFORMING_SYNCHRONIZATION; - } - - return SynchronizerState.IDLE; - - } - - /* (non-Javadoc) - * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#getStatReport(boolean) - */ - @Override - public String getStatReport(boolean showFinalReport) { - syncDurationInMs = System.currentTimeMillis() - syncStartedTimeStampInMs; - return this.getStatReport(syncDurationInMs, showFinalReport); - } - - /* (non-Javadoc) - * @see org.onap.aai.sparky.synchronizer.IndexSynchronizer#shutdown() - */ - @Override - public void shutdown() { - this.shutdownExecutors(); - } - - @Override - protected boolean isSyncDone() { - - int totalWorkOnHand = aaiWorkOnHand.get() + esWorkOnHand.get(); - - if (LOG.isDebugEnabled()) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC,indexName + ", isSyncDone(), totalWorkOnHand = " + totalWorkOnHand - + " all work enumerated = " + allWorkEnumerated); - } - - if (totalWorkOnHand > 0 || !allWorkEnumerated) { - return false; - } - - this.syncInProgress = false; - - return true; - } - - /* (non-Javadoc) - * @see org.onap.aai.sparky.synchronizer.AbstractEntitySynchronizer#clearCache() - */ - @Override - public void clearCache() { - - if (syncInProgress) { - LOG.debug(AaiUiMsgs.DEBUG_GENERIC, "Historical Entity Summarizer in progress, request to clear cache ignored"); - return; - } - - super.clearCache(); - this.resetCounters(); - if (entityCounters != null) { - entityCounters.clear(); - } - - allWorkEnumerated = false; - - } - -} diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/SyncHelper.java b/src/main/java/org/onap/aai/sparky/synchronizer/SyncHelper.java index 48331d0..3738acf 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/SyncHelper.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/SyncHelper.java @@ -206,72 +206,6 @@ public class SyncHelper { } - /** - * The Class HistoricalEntityCountSummaryTask. - */ - private class HistoricalEntityCountSummaryTask implements Runnable { - - /** - * Instantiates a new historical entity count summary task. - */ - public HistoricalEntityCountSummaryTask() {} - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - - long opStartTime = System.currentTimeMillis(); - MDC.setContextMap(contextMap); - LOG.info(AaiUiMsgs.HISTORICAL_ENTITY_COUNT_SUMMARIZER_STARTING, sdf.format(opStartTime) - .replaceAll(SynchronizerConstants.TIME_STD, SynchronizerConstants.TIME_CONFIG_STD)); - - try { - if (entityCounterHistorySummarizer == null) { - LOG.error(AaiUiMsgs.HISTORICAL_ENTITY_COUNT_SUMMARIZER_NOT_STARTED); - return; - } - - LOG.info(AaiUiMsgs.INFO_GENERIC, - "EntityCounterHistorySummarizer, starting syncrhonization"); - - entityCounterHistorySummarizer.performAction(SyncActions.SYNCHRONIZE); - - while (entityCounterHistorySummarizer - .getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { - Thread.sleep(1000); - } - - long opEndTime = System.currentTimeMillis(); - - LOG.info(AaiUiMsgs.HISTORICAL_SYNC_DURATION, - entityCounterHistorySummarizer.getControllerName(), - String.valueOf(opEndTime - opStartTime)); - - long taskFrequencyInMs = - syncConfig.getHistoricalEntitySummarizedFrequencyInMinutes() * 60 * 1000; - - if (syncConfig.isHistoricalEntitySummarizerEnabled()) { - String time = sdf.format(System.currentTimeMillis() + taskFrequencyInMs) - .replaceAll(SynchronizerConstants.TIME_STD, SynchronizerConstants.TIME_CONFIG_STD); - - LOG.info(AaiUiMsgs.HISTORICAL_SYNC_TO_BEGIN, time); - } - - - } catch (Exception exc) { - String message = "Caught an exception while attempting to populate entity country " - + "history elasticsearch table with an error cause = " - + ErrorUtil.extractStackTraceElements(5, exc); - LOG.error(AaiUiMsgs.ERROR_GENERIC, message); - } - - } - - } /** * Gets the first sync time. @@ -368,11 +302,6 @@ public class SyncHelper { cers.setEsDataProvider(esAdapter); syncController.registerEntitySynchronizer(cers); - GeoSynchronizer geo = new GeoSynchronizer(esConfig.getTopographicalSearchIndex()); - geo.setAaiDataProvider(aaiAdapter); - geo.setEsDataProvider(esAdapter); - syncController.registerEntitySynchronizer(geo); - if (syncConfig.isAutosuggestSynchronizationEnabled()) { initAutoSuggestionSynchronizer(esConfig, aaiAdapter, esAdapter, nonCachingRestProvider); initAggregationSynchronizer(esConfig, aaiAdapter, esAdapter, nonCachingRestProvider); @@ -389,14 +318,6 @@ public class SyncHelper { syncController.registerIndexCleaner(searchableIndexCleaner); - IndexCleaner geoIndexCleaner = new ElasticSearchIndexCleaner(nonCachingRestProvider, - esConfig.getTopographicalSearchIndex(), esConfig.getType(), esConfig.getIpAddress(), - esConfig.getHttpPort(), syncConfig.getScrollContextTimeToLiveInMinutes(), - syncConfig.getNumScrollContextItemsToRetrievePerRequest()); - - syncController.registerIndexCleaner(geoIndexCleaner); - - } catch (Exception exc) { String message = "Error: failed to sync with message = " + exc.getMessage(); LOG.error(AaiUiMsgs.ERROR_GENERIC, message); @@ -404,45 +325,6 @@ public class SyncHelper { } - /** - * Inits the entity counter history summarizer. - */ - private void initEntityCounterHistorySummarizer() { - - LOG.info(AaiUiMsgs.INFO_GENERIC, "initEntityCounterHistorySummarizer"); - - try { - entityCounterHistorySummarizer = new SyncController("entityCounterHistorySummarizer"); - - ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new RestClientBuilder()); - aaiAdapter.setCacheEnabled(false); - - RestClientBuilder clientBuilder = new RestClientBuilder(); - clientBuilder.setUseHttps(false); - - RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); - ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider, esConfig); - - IndexIntegrityValidator entityCounterHistoryValidator = - new IndexIntegrityValidator(nonCachingRestProvider, esConfig.getEntityCountHistoryIndex(), - esConfig.getType(), esConfig.getIpAddress(), esConfig.getHttpPort(), - esConfig.buildElasticSearchEntityCountHistoryTableConfig()); - - entityCounterHistorySummarizer.registerIndexValidator(entityCounterHistoryValidator); - - HistoricalEntitySummarizer historicalSummarizer = - new HistoricalEntitySummarizer(esConfig.getEntityCountHistoryIndex()); - historicalSummarizer.setAaiDataProvider(aaiAdapter); - historicalSummarizer.setEsDataProvider(esAdapter); - entityCounterHistorySummarizer.registerEntitySynchronizer(historicalSummarizer); - - } catch (Exception exc) { - String message = "Error: failed to sync with message = " + exc.getMessage(); - LOG.error(AaiUiMsgs.ERROR_GENERIC, message); - } - } - private List<String> getAutosuggestableEntitiesFromOXM() { Map<String, OxmEntityDescriptor> map = oxmModelLoader.getSuggestionSearchEntityDescriptors(); List<String> suggestableEntities = new ArrayList<String>(); @@ -583,13 +465,6 @@ public class SyncHelper { if (syncConfig.isConfigOkForStartupSync() || syncConfig.isConfigOkForPeriodicSync()) { initializeSyncController(); } - - if (syncConfig.isHistoricalEntitySummarizerEnabled()) { - initEntityCounterHistorySummarizer(); - } else { - LOG.info(AaiUiMsgs.INFO_GENERIC, "history summarizer disabled"); - } - // schedule startup synchronization if (syncConfig.isConfigOkForStartupSync()) { @@ -641,11 +516,6 @@ public class SyncHelper { } } - // schedule periodic synchronization - if (syncConfig.isHistoricalEntitySummarizerEnabled()) { - scheduleHistoricalCounterSyncTask(); - } - } catch (Exception exc) { String message = "Caught an exception while starting up the SyncHelper. Error cause = \n" + ErrorUtil.extractStackTraceElements(5, exc); @@ -653,17 +523,6 @@ public class SyncHelper { } } - /** - * Schedule historical counter sync task. - */ - private void scheduleHistoricalCounterSyncTask() { - long taskFrequencyInMs = - syncConfig.getHistoricalEntitySummarizedFrequencyInMinutes() * 60 * 1000; - historicalExecutor.scheduleWithFixedDelay(new HistoricalEntityCountSummaryTask(), 0, - taskFrequencyInMs, TimeUnit.MILLISECONDS); - LOG.info(AaiUiMsgs.INFO_GENERIC, - "Historical Entity Count Summarizer synchronization is enabled."); - } /** * Shutdown. diff --git a/src/main/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfiguration.java b/src/main/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfiguration.java index e6fd31d..2285950 100644 --- a/src/main/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfiguration.java +++ b/src/main/java/org/onap/aai/sparky/synchronizer/config/SynchronizerConfiguration.java @@ -29,6 +29,7 @@ import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Properties; +import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -60,7 +61,6 @@ public class SynchronizerConfiguration { if (instance == null) { instance = new SynchronizerConfiguration(); - instance.initialize(); } return instance; @@ -69,18 +69,20 @@ public class SynchronizerConfiguration { /** * Instantiates a new synchronizer configuration. */ - public SynchronizerConfiguration() { - // test method - } - + public SynchronizerConfiguration() throws Exception { + Properties props = ConfigHelper.loadConfigFromExplicitPath(CONFIG_FILE); + initialize(props); + } + + public SynchronizerConfiguration(Properties props) throws Exception { + initialize(props); + } /** * Initialize. * * @throws Exception the exception */ - protected void initialize() throws Exception { - - Properties props = ConfigHelper.loadConfigFromExplicitPath(CONFIG_FILE); + protected void initialize(Properties props) throws Exception { // parse config for startup sync try { @@ -173,11 +175,6 @@ public class SynchronizerConfiguration { nodesOnlyModifierEnabled = Boolean.parseBoolean(props.getProperty("synchronizer.applyNodesOnlyModifier")); - historicalEntitySummarizerEnabled = Boolean - .parseBoolean(props.getProperty("synchronizer.historicalEntitySummarizerEnabled", "true")); - historicalEntitySummarizedFrequencyInMinutes = Long.parseLong( - props.getProperty("synchronizer.historicalEntitySummarizedFrequencyInMinutes", "60")); - autosuggestSynchronizationEnabled = Boolean .parseBoolean(props.getProperty("synchronizer.autosuggestSynchronizationEnabled", "true")); @@ -210,24 +207,6 @@ public class SynchronizerConfiguration { this.displayVerboseQueueManagerStats = displayVerboseQueueManagerStats; } - public boolean isHistoricalEntitySummarizerEnabled() { - return historicalEntitySummarizerEnabled; - } - - public void setHistoricalEntitySummarizerEnabled(boolean historicalEntitySummarizerEnabled) { - this.historicalEntitySummarizerEnabled = historicalEntitySummarizerEnabled; - } - - public long getHistoricalEntitySummarizedFrequencyInMinutes() { - return historicalEntitySummarizedFrequencyInMinutes; - } - - public void setHistoricalEntitySummarizedFrequencyInMinutes( - long historicalEntitySummarizedFrequencyInMinutes) { - this.historicalEntitySummarizedFrequencyInMinutes = - historicalEntitySummarizedFrequencyInMinutes; - } - private int syncTaskInitialDelayInMs; private int syncTaskFrequencyInMs; @@ -262,13 +241,8 @@ public class SynchronizerConfiguration { private boolean nodesOnlyModifierEnabled; - private boolean historicalEntitySummarizerEnabled; - private boolean autosuggestSynchronizationEnabled; - private long historicalEntitySummarizedFrequencyInMinutes; - - private boolean configOkForStartupSync = true; private boolean configOkForPeriodicSync = true; @@ -413,7 +387,72 @@ public class SynchronizerConfiguration { public void setAutosuggestSynchronizationEnabled(boolean autosuggestSynchronizationEnabled) { this.autosuggestSynchronizationEnabled = autosuggestSynchronizationEnabled; } + + public Calendar getTargetSyncTime() { + + TimeZone tz = TimeZone.getTimeZone(getSyncTaskStartTimeTimeZone()); + Calendar targetSyncTime = Calendar.getInstance(tz); + + targetSyncTime.set(Calendar.HOUR_OF_DAY, getSyncTaskStartTimeHr()); + targetSyncTime.set(Calendar.MINUTE, getSyncTaskStartTimeMin()); + targetSyncTime.set(Calendar.SECOND, getSyncTaskStartTimeSec()); + + return targetSyncTime; + + } + + public long getDefaultInitialSyncDelayInMs(Calendar timeNow) { + + int taskFrequencyInDays = getSyncTaskFrequencyInDay(); + + long nextSyncTimeInMs = getNextSyncTime(getTargetSyncTime(), timeNow.getTimeInMillis(), + taskFrequencyInDays * 86400); + + /* + * If the the current time is after the scheduled start time, then delay + * by the initial task delay configuration value + */ + long delayUntilNextSyncInMs = Math.max(getSyncTaskInitialDelayInMs(), + nextSyncTimeInMs - timeNow.getTimeInMillis()); + + return delayUntilNextSyncInMs; + + } + + public long getNextSyncTime(Calendar syncTime, int taskFrequencyInSeconds) { + + TimeZone tz = TimeZone.getTimeZone(getSyncTaskStartTimeTimeZone()); + Calendar timeNow = Calendar.getInstance(tz); + + return getNextSyncTime(syncTime, timeNow.getTimeInMillis(), taskFrequencyInSeconds); + } + + /** + * Gets the first sync time. + * + * @param calendar + * the calendar + * @param timeNow + * the time now in ms + * @param taskFrequencyInMs + * task period in ms + * @return the first sync time + */ + public long getNextSyncTime(Calendar syncTime, long timeNowInMs, int taskFrequencyInSeconds) { + if (taskFrequencyInSeconds == 0) { + return 0; + } else if (timeNowInMs > syncTime.getTimeInMillis()) { + + /* + * If current time is after the scheduled sync start time, then + * we'll skip ahead to the next sync time period + */ + + syncTime.add(Calendar.SECOND, taskFrequencyInSeconds); + } + return syncTime.getTimeInMillis(); + } /* (non-Javadoc) * @see java.lang.Object#toString() */ |