List of usage examples for java.util Date compareTo
public int compareTo(Date anotherDate)
From source file:org.slc.sli.dashboard.manager.impl.PopulationManagerImpl.java
/** * Adds the current session grades to the student in a easily retrievable * manner./* ww w.j a v a 2s . com*/ * * @param student * @param sectionId */ @SuppressWarnings("unchecked") private void addCurrentSessionGrades(GenericEntity student, String sectionId) { final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Sort the grades SortedSet<GenericEntity> sortedList = new TreeSet<GenericEntity>(new Comparator<GenericEntity>() { @Override public int compare(GenericEntity a, GenericEntity b) { Object dateA = a.get(Constants.ATTR_DATE_FULFILLED); Object dateB = b.get(Constants.ATTR_DATE_FULFILLED); if (dateA == null) { return 1; } else if (dateB == null) { return -1; } return ((Date) dateA).compareTo((Date) dateB); } }); // Get the term and year try { Map<String, Object> transcripts = (Map<String, Object>) student.get(Constants.ATTR_TRANSCRIPT); if (transcripts == null) { return; } List<Map<String, Object>> stuSectAssocs = (List<Map<String, Object>>) transcripts .get(Constants.ATTR_STUDENT_SECTION_ASSOC); if (stuSectAssocs == null) { return; } // figure out what the start and end dates are for the current // session List<Date> dates = getSessionDates(stuSectAssocs, sectionId); Date sessionStart = (dates == null) ? null : dates.get(0); Date sessionEnd = (dates == null) ? null : dates.get(1); // next we ensure that gradebook entries belong to the current // session // iterate and add to letter grade List<Map<String, Object>> gradeEntries = (List<Map<String, Object>>) student .get(Constants.ATTR_STUDENT_GRADEBOOK_ENTRIES); if (gradeEntries == null) { return; } for (Map<String, Object> currentGrade : gradeEntries) { GenericEntity gradeDate = new GenericEntity(); // get the grade itself Object grade = currentGrade.get(Constants.ATTR_LETTER_GRADE_EARNED); if (grade == null) { grade = currentGrade.get(Constants.ATTR_NUMERIC_GRADE_EARNED); if (grade == null) { continue; } } // when was it earned? try { Object dateString = currentGrade.get(Constants.ATTR_DATE_FULFILLED); // only keep it if it belongs to this session, or there is // no date // associated with it or the current session if (dateString != null) { Date date = formatter.parse((String) dateString); if (((sessionStart == null || sessionStart.compareTo(date) <= 0) && (sessionEnd == null || sessionEnd.compareTo(date) >= 0))) { gradeDate.put(Constants.ATTR_DATE_FULFILLED, date); } else { // this grade does not belong in the current session continue; } } } catch (ParseException e) { LOG.error("Error parsing dates for a Current Section grade."); } gradeDate.put(Constants.ATTR_GRADE_EARNED, grade); sortedList.add(gradeDate); } int count = 0; for (GenericEntity entity : sortedList) { student.put("currentSession-" + count++, entity); } } catch (ClassCastException ex) { LOG.error("Error occured processing Gradebook Entries", ex); } }
From source file:eu.europa.esig.dss.validation.process.ltv.ControlTimeSliding.java
/** * @param params/*from w w w. ja v a 2 s . c om*/ * @param certificateChain * @return */ private ControlTimeSlidingConclusion process(final ProcessParameters params, final XmlDom certificateChain) { final ControlTimeSlidingConclusion conclusion = new ControlTimeSlidingConclusion(); final String signingCertificateId = certificateChain.getValue("./ChainCertificate[1]/@Id"); final List<XmlDom> chainCertificates = certificateChain.getElements("./ChainCertificate"); Collections.reverse(chainCertificates); /** * 2) For each certificate in the chain starting from the first certificate (the certificate issued by the trust * anchor), do the following:<br> */ for (final XmlDom chainCertificate : chainCertificates) { final String certificateId = getCertificateId(chainCertificate); final XmlNode certificateNode = controlTimeSlidingData.addChild(AttributeValue.CERTIFICATE, StringUtils.EMPTY); certificateNode.setAttribute(AttributeValue.CERTIFICATE_ID, String.valueOf(certificateId)); final XmlDom certificate = params.getCertificate(certificateId); final boolean isTrusted = certificate.getBoolValue("./Trusted/text()"); if (isTrusted) { continue; } if (StringUtils.equals(signingCertificateId, certificateId)) { /** * (See NOTE 1) Concerning the trust anchor, it must be checked if it is still trusted at the current * date/time. Other checks are not necessary.<br> */ final XmlNode constraintNode = addConstraint(MessageTag.CTS_WITSS); final String status = InvolvedServiceInfo.getStatus(certificate); constraintNode.addChild(NodeName.STATUS, NodeValue.OK); constraintNode.addChild(NodeName.INFO).setAttribute(AttributeValue.TRUSTED_SERVICE_STATUS, status); final boolean underSupervision = InvolvedServiceInfo.isSERVICE_STATUS_UNDERSUPERVISION(status); final boolean supervisionInCessation = InvolvedServiceInfo .isSERVICE_STATUS_SUPERVISIONINCESSATION(status); final boolean accredited = InvolvedServiceInfo.isSERVICE_STATUS_ACCREDITED(status); if (!underSupervision && !supervisionInCessation && !accredited) { /** * ...where the trust anchor is broken at a known date by initialising control-time to this date/time.<br> */ if (status.isEmpty()) { // Trusted service is unknown final String serviceName = InvolvedServiceInfo.getServiceName(certificate); LOG.warn("The status of the service is unknown: (serviceName: " + serviceName + ")"); } else { final Date statusEndDate = InvolvedServiceInfo.getEndDate(certificate); controlTime = statusEndDate; addControlTime(constraintNode); } } } /** * - a) Find revocation status information satisfying the following:<br> * - - The revocation status information is consistent with the rules conditioning its use to check the * revocation status of the considered certificate. For instance, in the case of a CRL, it shall satisfy the * checks described in (see clause 6.3).<br> * * TODO: 20130704 by bielecro: To notify ETSI --> (see clause 6.3) is not the right clause.<br> */ XmlNode constraintNode = addConstraint(MessageTag.CTS_DRIE); final boolean revocationExists = certificate.exists("./Revocation"); if (!revocationExists) { constraintNode.addChild(NodeName.STATUS, NodeValue.KO); conclusion.setIndication(Indication.INDETERMINATE); conclusion.setSubIndication(SubIndication.NO_POE); return conclusion; } final Date revocationIssuingTime = certificate.getTimeValue("./Revocation/IssuingTime/text()"); final String formatedRevocationIssuingTime = DSSUtils.formatDate(revocationIssuingTime); constraintNode.addChild(NodeName.STATUS, NodeValue.OK); constraintNode.addChild(NodeName.INFO).setAttribute(AttributeName.REVOCATION_ISSUING_TIME, formatedRevocationIssuingTime); final Date notAfterTime = certificate.getTimeValue("./NotAfter/text()"); final Date notBeforeTime = certificate.getTimeValue("./NotBefore/text()"); /** * (See NOTE 2)<br> * TODO: ...(for instance, using the CRL extension expiredCertOnCRL (OID: 2.5.29.60)) This check need to be * added to the revocation information retrieval. */ constraintNode = addConstraint(MessageTag.CTS_ICNEAIDORSI); if (revocationIssuingTime.before(notBeforeTime) || revocationIssuingTime.after(notAfterTime)) { constraintNode.addChild(NodeName.STATUS, NodeValue.KO); conclusion.setIndication(Indication.INDETERMINATE); conclusion.setSubIndication(SubIndication.NO_POE); return conclusion; } constraintNode.addChild(NodeName.STATUS, NodeValue.OK); /** * - - The issuance date of the revocation status information is before control-time. If more than one * revocation status is found, consider the most recent one and go to the next step. If there is no such * information, terminate with INDETERMINATE/NO_POE:<br> */ constraintNode = addConstraint(MessageTag.CTS_IIDORSIBCT); if (!revocationIssuingTime.before(controlTime)) { constraintNode.addChild(NodeName.STATUS, NodeValue.KO); addControlTime(constraintNode); conclusion.setIndication(Indication.INDETERMINATE); conclusion.setSubIndication(SubIndication.NO_POE); return conclusion; } constraintNode.addChild(NodeName.STATUS, NodeValue.OK); /** * - b) If the set of POEs contains a proof of existence of the certificate and the revocation status * information at (or before) control-time, go to step c). Otherwise, terminate with INDETERMINATE/NO_POE. */ constraintNode = addConstraint(MessageTag.CTS_DSOPCPOEOC); final boolean poeExists = poe.getCertificatePOE(certificateId, controlTime); if (!poeExists || (revocationIssuingTime.compareTo(controlTime) > 0)) { constraintNode.addChild(NodeName.STATUS, NodeValue.KO); conclusion.setIndication(Indication.INDETERMINATE); conclusion.setSubIndication(SubIndication.NO_POE); return conclusion; } constraintNode.addChild(NodeName.STATUS, NodeValue.OK); /** * - c) Update the value of control-time as follows:<br> */ constraintNode = addConstraint(MessageTag.CTS_SCT); addControlTime(constraintNode); final boolean revoked = !certificate.getBoolValue("./Revocation/Status/text()"); /** * - - If the certificate is marked as revoked in the revocation status information, set control-time to the * revocation date.<br> */ if (revoked) { final Date revocationDate = certificate.getTimeValue("./Revocation/DateTime/text()"); controlTime = revocationDate; final String formatedRevocationDate = DSSUtils.formatDate(revocationDate); constraintNode.addChild(NodeName.INFO, NodeValue.CTS_CTSTRT_LABEL); constraintNode.addChild(NodeName.INFO).setAttribute(AttributeName.REVOCATION_TIME, formatedRevocationDate); } else { /** * - - If the certificate is not marked as revoked.<br> * - - - - If the revocation status information is not considered "fresh", set control-time to the issuance * date of the revocation status information.<br> */ final long revocationDeltaTime = controlTime.getTime() - revocationIssuingTime.getTime(); if (revocationDeltaTime > constraintData.getMaxRevocationFreshness()) { controlTime = revocationIssuingTime; constraintNode.addChild(NodeName.INFO, NodeValue.CTS_CTSTRIT_LABEL); final XmlNode xmlNode = constraintNode.addChild(NodeName.INFO, MessageTag.BBB_XCV_IRIF_ANS); xmlNode.setAttribute(AttributeValue.CERTIFICATE_ID, String.valueOf(certificateId)) .setAttribute(AttributeName.REVOCATION_ISSUING_TIME, formatedRevocationIssuingTime); } /** * - - - - Otherwise, the value of control-time is not changed.<br> */ } /** * - d) Apply the cryptographic constraints to the certificate and the revocation status information. If the * certificate (or the revocation status information) does not match these constraints, set control-time to the * lowest time up to which the listed algorithms were considered reliable.<br> */ checkDigestAlgoExpirationDate(certificate, constraintNode, NodeValue.CTS_CTSTETOCSA_LABEL); checkEncryptionAlgoExpirationDate(certificate, constraintNode, NodeValue.CTS_CTSTETOCSA_LABEL); final XmlDom revocation = certificate.getElement("./Revocation"); checkDigestAlgoExpirationDate(revocation, constraintNode, NodeValue.CTS_CTSTETORSA_LABEL); checkEncryptionAlgoExpirationDate(revocation, constraintNode, NodeValue.CTS_CTSTETORSA_LABEL); /** * 3) Continue with the next certificate in the chain or, if no further certificate exists, terminate with * VALID and the calculated control-time.<br> */ } /** * NOTE 1: In step 1, initialising control-time with current date/time assumes that the trust anchor is still * trusted at the current date/time. The algorithm can capture the very exotic case where the trust anchor is * broken (or becomes untrusted for any other reason) at a known date by initialising control-time to this * date/time.<br> * * NOTE 2: The rational of step 2-a) is to check that the revocation status information is "in-scope" for the * given certificate. In other words, the rationale is to check that the revocation status information is reliable * to be used to ascertain the revocation status of the given certificate. For instance, this includes the fact * the certificate is not expired at the issuance date of the revocation status information, unless the issuing CA * states that its issues revocation information status for expired certificates (for instance, using the CRL * extension expiredCertOnCRL).<br> * * NOTE 3: If the certificate (or the revocation status information) was authentic, but the signature has been * faked exploiting weaknesses of the algorithms used, this is assumed only to be possible after the date the * algorithms are declared to be no longer acceptable. Therefore, the owner of the original key pair is assumed to * having been under control of his key up to that date. This is the rational of sliding control-time in step * 2-d).<br> * * NOTE 4: For more readability, the algorithm above implicitly assumes that the revocation information status is * signed by the certificate's issuer which is the most traditional revocation setting but not the only one. The * same algorithm can be adapted to the cases where the revocation information status has its own certificate * chain by applying the control-time sliding process to this chain which would output a control-time that has to * be compared to the control-time associated to the certificate. */ conclusion.setIndication(Indication.VALID); conclusion.addInfo().setAttribute(AttributeValue.CONTROL_TIME, DSSUtils.formatDate(controlTime)); return conclusion; }
From source file:org.nuclos.server.ruleengine.RuleInterface.java
public boolean isPeriodOverlapping(Date datePeriod1From, Date datePeriod1Until, Date datePeriod2From, Date datePeriod2Until) throws NuclosBusinessRuleException { if (isPeriodValid(datePeriod1From, datePeriod1Until) && isPeriodValid(datePeriod2From, datePeriod2Until)) { if (datePeriod1From != null && datePeriod1From.compareTo(datePeriod2From) < 0) { // period 1 is first one return !(datePeriod1Until.compareTo(datePeriod2From) < 0); } else if (datePeriod2From != null && datePeriod2From.compareTo(datePeriod1From) < 0) { // period 2 is first one return !(datePeriod2Until.compareTo(datePeriod1From) < 0); } else {/* w w w.j av a2s . co m*/ return true; } } else { throw new NuclosBusinessRuleException("rule.interface.error.9"); //"Eine der Perioden ist nicht g\u00fcltig. G\u00fcltig Von muss vor G\u00fcltig bis liegen."); } }
From source file:org.apache.falcon.workflow.engine.OozieWorkflowEngine.java
@SuppressWarnings("MagicConstant") protected Map<String, List<CoordinatorAction>> getCoordActions(Entity entity, Date start, Date end, List<LifeCycle> lifeCycles) throws FalconException { Map<String, List<BundleJob>> bundlesMap = findBundles(entity); Map<String, List<CoordinatorAction>> actionsMap = new HashMap<String, List<CoordinatorAction>>(); for (Map.Entry<String, List<BundleJob>> entry : bundlesMap.entrySet()) { String cluster = entry.getKey(); List<BundleJob> bundles = entry.getValue(); OozieClient client = OozieClientFactory.get(cluster); List<CoordinatorJob> applicableCoords = getApplicableCoords(client, start, end, bundles, lifeCycles); List<CoordinatorAction> actions = new ArrayList<CoordinatorAction>(); int maxRetentionInstancesCount = Integer .valueOf(RuntimeProperties.get().getProperty("retention.instances.displaycount", "2")); int retentionInstancesCount = 0; for (CoordinatorJob coord : applicableCoords) { Date nextMaterializedTime = coord.getNextMaterializedTime(); if (nextMaterializedTime == null) { continue; }/*w ww. j a v a 2 s . co m*/ boolean retentionCoord = isRetentionCoord(coord); Frequency freq = createFrequency(String.valueOf(coord.getFrequency()), coord.getTimeUnit()); TimeZone tz = EntityUtil.getTimeZone(coord.getTimeZone()); Date iterEnd = ((nextMaterializedTime.before(end) || retentionCoord) ? nextMaterializedTime : end); Calendar endCal = Calendar.getInstance(EntityUtil.getTimeZone(coord.getTimeZone())); endCal.setTime(EntityUtil.getNextStartTime(coord.getStartTime(), freq, tz, iterEnd)); endCal.add(freq.getTimeUnit().getCalendarUnit(), -(Integer.valueOf((coord.getFrequency())))); while (start.compareTo(endCal.getTime()) <= 0) { if (retentionCoord) { if (retentionInstancesCount >= maxRetentionInstancesCount) { break; } retentionInstancesCount++; } int sequence = EntityUtil.getInstanceSequence(coord.getStartTime(), freq, tz, endCal.getTime()); String actionId = coord.getId() + "@" + sequence; addCoordAction(client, actions, actionId); endCal.add(freq.getTimeUnit().getCalendarUnit(), -(Integer.valueOf((coord.getFrequency())))); } } actionsMap.put(cluster, actions); } return actionsMap; }
From source file:org.alfresco.solr.HandlerReportBuilder.java
/** * Adds a core summary/*from www.j a va 2 s . c o m*/ * @param cname * @param detail * @param hist * @param values * @param srv * @param report * @throws IOException */ public static void addCoreSummary(TrackerRegistry trackerRegistry, String cname, boolean detail, boolean hist, boolean values, InformationServer srv, NamedList<Object> report) throws IOException { NamedList<Object> coreSummary = new SimpleOrderedMap<Object>(); coreSummary.addAll((SimpleOrderedMap<Object>) srv.getCoreStats()); MetadataTracker metaTrkr = trackerRegistry.getTrackerForCore(cname, MetadataTracker.class); TrackerState metadataTrkrState = metaTrkr.getTrackerState(); long lastIndexTxCommitTime = metadataTrkrState.getLastIndexedTxCommitTime(); long lastIndexedTxId = metadataTrkrState.getLastIndexedTxId(); long lastTxCommitTimeOnServer = metadataTrkrState.getLastTxCommitTimeOnServer(); long lastTxIdOnServer = metadataTrkrState.getLastTxIdOnServer(); Date lastIndexTxCommitDate = new Date(lastIndexTxCommitTime); Date lastTxOnServerDate = new Date(lastTxCommitTimeOnServer); long transactionsToDo = lastTxIdOnServer - lastIndexedTxId; if (transactionsToDo < 0) { transactionsToDo = 0; } AclTracker aclTrkr = trackerRegistry.getTrackerForCore(cname, AclTracker.class); TrackerState aclTrkrState = aclTrkr.getTrackerState(); long lastIndexChangeSetCommitTime = aclTrkrState.getLastIndexedChangeSetCommitTime(); long lastIndexedChangeSetId = aclTrkrState.getLastIndexedChangeSetId(); long lastChangeSetCommitTimeOnServer = aclTrkrState.getLastChangeSetCommitTimeOnServer(); long lastChangeSetIdOnServer = aclTrkrState.getLastChangeSetIdOnServer(); Date lastIndexChangeSetCommitDate = new Date(lastIndexChangeSetCommitTime); Date lastChangeSetOnServerDate = new Date(lastChangeSetCommitTimeOnServer); long changeSetsToDo = lastChangeSetIdOnServer - lastIndexedChangeSetId; if (changeSetsToDo < 0) { changeSetsToDo = 0; } long nodesToDo = 0; long remainingTxTimeMillis = 0; if (transactionsToDo > 0) { // We now use the elapsed time as seen by the single thread farming out metadata indexing double meanDocsPerTx = srv.getTrackerStats().getMeanDocsPerTx(); double meanNodeElaspedIndexTime = srv.getTrackerStats().getMeanNodeElapsedIndexTime(); nodesToDo = (long) (transactionsToDo * meanDocsPerTx); remainingTxTimeMillis = (long) (nodesToDo * meanNodeElaspedIndexTime); } Date now = new Date(); Date end = new Date(now.getTime() + remainingTxTimeMillis); Duration remainingTx = new Duration(now, end); long remainingChangeSetTimeMillis = 0; if (changeSetsToDo > 0) { // We now use the elapsed time as seen by the single thread farming out alc indexing double meanAclsPerChangeSet = srv.getTrackerStats().getMeanAclsPerChangeSet(); double meanAclElapsedIndexTime = srv.getTrackerStats().getMeanAclElapsedIndexTime(); remainingChangeSetTimeMillis = (long) (changeSetsToDo * meanAclsPerChangeSet * meanAclElapsedIndexTime); } now = new Date(); end = new Date(now.getTime() + remainingChangeSetTimeMillis); Duration remainingChangeSet = new Duration(now, end); NamedList<Object> ftsSummary = new SimpleOrderedMap<Object>(); long remainingContentTimeMillis = 0; srv.addFTSStatusCounts(ftsSummary); long cleanCount = ((Long) ftsSummary.get("Node count with FTSStatus Clean")).longValue(); long dirtyCount = ((Long) ftsSummary.get("Node count with FTSStatus Dirty")).longValue(); long newCount = ((Long) ftsSummary.get("Node count with FTSStatus New")).longValue(); long nodesInIndex = ((Long) coreSummary.get("Alfresco Nodes in Index")); long contentYetToSee = nodesInIndex > 0 ? nodesToDo * (cleanCount + dirtyCount + newCount) / nodesInIndex : 0; ; if (dirtyCount + newCount + contentYetToSee > 0) { // We now use the elapsed time as seen by the single thread farming out alc indexing double meanContentElapsedIndexTime = srv.getTrackerStats().getMeanContentElapsedIndexTime(); remainingContentTimeMillis = (long) ((dirtyCount + newCount + contentYetToSee) * meanContentElapsedIndexTime); } now = new Date(); end = new Date(now.getTime() + remainingContentTimeMillis); Duration remainingContent = new Duration(now, end); coreSummary.add("FTS", ftsSummary); Duration txLag = new Duration(lastIndexTxCommitDate, lastTxOnServerDate); if (lastIndexTxCommitDate.compareTo(lastTxOnServerDate) > 0) { txLag = new Duration(); } long txLagSeconds = (lastTxCommitTimeOnServer - lastIndexTxCommitTime) / 1000; if (txLagSeconds < 0) { txLagSeconds = 0; } Duration changeSetLag = new Duration(lastIndexChangeSetCommitDate, lastChangeSetOnServerDate); if (lastIndexChangeSetCommitDate.compareTo(lastChangeSetOnServerDate) > 0) { changeSetLag = new Duration(); } long changeSetLagSeconds = (lastChangeSetCommitTimeOnServer - lastIndexChangeSetCommitTime) / 1000; if (txLagSeconds < 0) { txLagSeconds = 0; } ContentTracker contentTrkr = trackerRegistry.getTrackerForCore(cname, ContentTracker.class); TrackerState contentTrkrState = contentTrkr.getTrackerState(); // Leave ModelTracker out of this check, because it is common boolean aTrackerIsRunning = aclTrkrState.isRunning() || metadataTrkrState.isRunning() || contentTrkrState.isRunning(); coreSummary.add("Active", aTrackerIsRunning); ModelTracker modelTrkr = trackerRegistry.getModelTracker(); TrackerState modelTrkrState = modelTrkr.getTrackerState(); coreSummary.add("ModelTracker Active", modelTrkrState.isRunning()); coreSummary.add("ContentTracker Active", contentTrkrState.isRunning()); coreSummary.add("MetadataTracker Active", metadataTrkrState.isRunning()); coreSummary.add("AclTracker Active", aclTrkrState.isRunning()); // TX coreSummary.add("Last Index TX Commit Time", lastIndexTxCommitTime); coreSummary.add("Last Index TX Commit Date", lastIndexTxCommitDate); coreSummary.add("TX Lag", txLagSeconds + " s"); coreSummary.add("TX Duration", txLag.toString()); coreSummary.add("Timestamp for last TX on server", lastTxCommitTimeOnServer); coreSummary.add("Date for last TX on server", lastTxOnServerDate); coreSummary.add("Id for last TX on server", lastTxIdOnServer); coreSummary.add("Id for last TX in index", lastIndexedTxId); coreSummary.add("Approx transactions remaining", transactionsToDo); coreSummary.add("Approx transaction indexing time remaining", remainingTx.largestComponentformattedString()); // Change set coreSummary.add("Last Index Change Set Commit Time", lastIndexChangeSetCommitTime); coreSummary.add("Last Index Change Set Commit Date", lastIndexChangeSetCommitDate); coreSummary.add("Change Set Lag", changeSetLagSeconds + " s"); coreSummary.add("Change Set Duration", changeSetLag.toString()); coreSummary.add("Timestamp for last Change Set on server", lastChangeSetCommitTimeOnServer); coreSummary.add("Date for last Change Set on server", lastChangeSetOnServerDate); coreSummary.add("Id for last Change Set on server", lastChangeSetIdOnServer); coreSummary.add("Id for last Change Set in index", lastIndexedChangeSetId); coreSummary.add("Approx change sets remaining", changeSetsToDo); coreSummary.add("Approx change set indexing time remaining", remainingChangeSet.largestComponentformattedString()); coreSummary.add("Approx content indexing time remaining", remainingContent.largestComponentformattedString()); // Stats coreSummary.add("Model sync times (ms)", srv.getTrackerStats().getModelTimes().getNamedList(detail, hist, values)); coreSummary.add("Acl index time (ms)", srv.getTrackerStats().getAclTimes().getNamedList(detail, hist, values)); coreSummary.add("Node index time (ms)", srv.getTrackerStats().getNodeTimes().getNamedList(detail, hist, values)); coreSummary.add("Docs/Tx", srv.getTrackerStats().getTxDocs().getNamedList(detail, hist, values)); coreSummary.add("Doc Transformation time (ms)", srv.getTrackerStats().getDocTransformationTimes().getNamedList(detail, hist, values)); // Model Map<String, Set<String>> modelErrors = srv.getModelErrors(); if (modelErrors.size() > 0) { NamedList<Object> errorList = new SimpleOrderedMap<Object>(); for (Map.Entry<String, Set<String>> modelNameToErrors : modelErrors.entrySet()) { errorList.add(modelNameToErrors.getKey(), modelNameToErrors.getValue()); } coreSummary.add( "Model changes are not compatible with the existing data model and have not been applied", errorList); } report.add(cname, coreSummary); }
From source file:org.apache.lens.cube.metadata.CubeMetastoreClient.java
private LatestInfo getNextLatestOfDimtable(Table hiveTable, String timeCol, final int timeColIndex, UpdatePeriod updatePeriod, Map<String, String> nonTimePartSpec) throws HiveException { // getClient().getPartitionsByNames(tbl, partNames) List<Partition> partitions; try {//from w ww. ja v a 2 s . c o m partitions = getClient().getPartitionsByFilter(hiveTable, StorageConstants.getPartFilter(nonTimePartSpec)); filterPartitionsByUpdatePeriod(partitions, updatePeriod); filterPartitionsByNonTimeParts(partitions, nonTimePartSpec, timeCol); } catch (TException e) { throw new HiveException(e); } // tree set contains partitions with timestamp as value for timeCol, in // descending order TreeSet<Partition> allPartTimeVals = new TreeSet<>(new Comparator<Partition>() { @Override public int compare(Partition o1, Partition o2) { Date partDate1 = getPartDate(o1, timeColIndex); Date partDate2 = getPartDate(o2, timeColIndex); if (partDate1 != null && partDate2 == null) { return -1; } else if (partDate1 == null && partDate2 != null) { return 1; } else if (partDate1 == null) { return o2.getTPartition().compareTo(o1.getTPartition()); } else if (!partDate2.equals(partDate1)) { return partDate2.compareTo(partDate1); } else { return o2.getTPartition().compareTo(o1.getTPartition()); } } }); for (Partition part : partitions) { if (!isLatestPartOfDimtable(part)) { Date partDate = getPartDate(part, timeColIndex); if (partDate != null) { allPartTimeVals.add(part); } } } Iterator<Partition> it = allPartTimeVals.iterator(); it.next(); // Skip itself. We have to find next latest. LatestInfo latest = null; if (it.hasNext()) { Partition nextLatest = it.next(); latest = new LatestInfo(); latest.setPart(nextLatest); Map<String, String> latestParams = LensUtil.getHashMap(getLatestPartTimestampKey(timeCol), nextLatest.getValues().get(timeColIndex)); latest.addLatestPartInfo(timeCol, new LatestPartColumnInfo(latestParams)); } return latest; }
From source file:com.sfs.whichdoctor.search.sql.PersonSqlHandler.java
/** * Construct the SQL string, description and parameters. * * @param objCriteria Object containing search criteria values * @param objConstraints Object containing search constraint values * * @return Map containing a String[] { sql, description } => * Collection< Object > parameters * * @throws IllegalArgumentException the illegal argument exception *//* w ww . ja v a 2 s .com*/ @SuppressWarnings("unchecked") public final Map<String[], Collection<Object>> construct(final Object objCriteria, final Object objConstraints) throws IllegalArgumentException { PersonBean searchCriteria = null; PersonBean searchConstraints = null; if (objCriteria instanceof PersonBean) { searchCriteria = (PersonBean) objCriteria; } if (objConstraints instanceof PersonBean) { searchConstraints = (PersonBean) objConstraints; } if (searchCriteria == null) { throw new IllegalArgumentException("The search criteria must " + "be a valid PersonBean"); } if (searchConstraints == null) { throw new IllegalArgumentException("The search constraints must " + "be a valid PersonBean"); } StringBuffer sqlWHERE = new StringBuffer(); StringBuffer description = new StringBuffer(); Collection<Object> parameters = new ArrayList<Object>(); if (searchCriteria.getTags() != null) { try { for (TagBean tag : searchCriteria.getTags()) { Map<String[], Collection<Object>> results = this.tagSearchDAO.construct(tag, new TagBean()); for (String[] index : results.keySet()) { String tagWHERE = index[0]; String tagDescription = index[1]; Collection<Object> tagParameters = results.get(index); if (tagWHERE.compareTo("") != 0) { // A WHERE condition is defined // Add to the SQL WHERE clause sqlWHERE.append( " " + this.getSQL().getValue("person/searchTags") + " WHERE " + tagWHERE + ")"); /* Add to the description and process the arrays */ description.append(tagDescription); if (tagParameters != null) { parameters.addAll(tagParameters); } } } } } catch (Exception e) { dataLogger.error("Error setting tag search options: " + e.getMessage()); } } /* Basic Search is used to locate a person based on their full name */ if (StringUtils.isNotBlank(searchCriteria.getBasicSearch())) { String searchString = searchCriteria.getBasicSearch().trim(); int identifier = 0; try { identifier = Integer.parseInt(searchString); } catch (NumberFormatException nfe) { dataLogger.debug("Error parsing Basic Search: " + nfe.getMessage()); } // If the search string ends with ) then meta-data is probably included if (searchString.endsWith(")") && searchString.indexOf(" (") > 0) { // The search string has brackets - remove the brackets and their content. searchString = searchString.substring(0, searchString.lastIndexOf(" (")); } if (identifier == 0) { sqlWHERE.append(" AND (concat(title.Name, ' ', people.FirstName, ' ', "); sqlWHERE.append("people.LastName) LIKE ? OR concat(title.Name, ' ', "); sqlWHERE.append("people.PreferredName, ' ', people.LastName) LIKE ? "); sqlWHERE.append("OR concat(title.Name,' ', people.Lastname) LIKE ? "); sqlWHERE.append("OR concat(title.Name, ' ', people.FirstName, ' ', "); sqlWHERE.append("people.MaidenName) LIKE ? )"); description.append(" and a name like '" + searchString + "'"); for (int i = 0; i < 4; i++) { parameters.add("%" + searchString + "%"); } } else { sqlWHERE.append(" AND (people.PersonIdentifier = ?)"); description.append(" and a MIN equal to '" + identifier + "'"); parameters.add(identifier); } } /* * Name field is tricky. Need to build a conjoint first/last search * field */ if (searchCriteria.getFirstName() != null) { if (searchCriteria.getFirstName().compareTo("") != 0) { sqlWHERE.append(" AND (people.FirstName LIKE ? " + "OR people.PreferredName LIKE ?)"); description.append(" and a first name like '" + searchCriteria.getFirstName() + "'"); parameters.add(searchCriteria.getFirstName() + "%"); parameters.add(searchCriteria.getFirstName() + "%"); } } if (searchCriteria.getLastName() != null) { if (searchCriteria.getLastName().compareTo("") != 0) { sqlWHERE.append(" AND people.LastName LIKE ?"); description .append(" and a last name like '" + DataFilter.getHtml(searchCriteria.getLastName()) + "'"); parameters.add(searchCriteria.getLastName() + "%"); } } if (searchCriteria.getId() > 0) { boolean maximum = false; boolean minimum = false; boolean range = false; boolean single = true; if (searchConstraints.getId() < 0) { minimum = true; single = false; } if (searchConstraints.getId() > 0) { range = true; single = false; } if (searchConstraints.getId() == 999999999) { maximum = true; range = false; single = false; } if (minimum) { // Get values less than supplied ID sqlWHERE.append(" AND people.PersonId <= ?"); description.append(" and a person Id like '" + searchCriteria.getId() + "'"); parameters.add(searchCriteria.getId()); } if (maximum) { maximum = true; // Get values greater than supplied ID sqlWHERE.append(" AND people.PersonId >= ?"); description.append(" and a person Id greater than '" + searchCriteria.getId() + "'"); parameters.add(searchCriteria.getId()); } if (range) { // Search Constraints between A and B if (searchCriteria.getId() > searchConstraints.getId()) { // A greater than B sqlWHERE.append(" AND people.PersonId BETWEEN ? AND ?"); description.append(" and a person Id between '" + searchConstraints.getId() + "' and '" + searchCriteria.getId() + "'"); parameters.add(searchConstraints.getId()); parameters.add(searchCriteria.getId()); } else if (searchCriteria.getId() < searchConstraints.getId()) { // B greater than A sqlWHERE.append(" AND people.PersonId BETWEEN ? AND ?"); description.append(" and a person Id between '" + searchCriteria.getId() + "' and '" + searchConstraints.getId() + "'"); parameters.add(searchCriteria.getId()); parameters.add(searchConstraints.getId()); } else { // A = B sqlWHERE.append(" AND people.PersonId = ?"); description.append(" and a person Id equal to '" + searchCriteria.getId() + "'"); parameters.add(searchCriteria.getId()); } } if (single) { sqlWHERE.append(" AND people.PersonId = ?"); description.append(" and a person Id equal to '" + searchCriteria.getId() + "'"); parameters.add(searchCriteria.getId()); } } if (searchCriteria.getPersonIdentifier() > 0) { final int pidCriteria = searchCriteria.getPersonIdentifier(); final int pidConstraints = searchConstraints.getPersonIdentifier(); if (pidCriteria > 0) { boolean maximum = false; boolean minimum = false; boolean range = false; boolean single = true; if (pidConstraints < 0) { minimum = true; single = false; } if (pidConstraints > 0) { range = true; single = false; } if (pidConstraints == 999999999) { maximum = true; range = false; single = false; } if (minimum) { // Get values less than supplied MIN sqlWHERE.append(" AND people.PersonIdentifier <= ?"); description.append(" and a MIN less than '" + pidCriteria + "'"); parameters.add(pidCriteria); } if (maximum) { maximum = true; // Get values greater than supplied MIN sqlWHERE.append(" AND people.PersonIdentifier >= ?"); description.append(" and a MIN greater than '" + pidCriteria + "'"); parameters.add(pidCriteria); } if (range) { // Search Constraints between A and B if (pidCriteria > pidConstraints) { // A greater than B sqlWHERE.append(" AND people.PersonIdentifier BETWEEN ? AND ?"); description.append(" and a MIN between '" + pidConstraints + "' and '" + pidCriteria + "'"); parameters.add(pidConstraints); parameters.add(pidCriteria); } else if (pidCriteria < pidConstraints) { // B greater than A sqlWHERE.append(" AND people.PersonIdentifier BETWEEN ? AND ?"); description.append(" and a MIN between '" + pidCriteria + "' and '" + pidConstraints + "'"); parameters.add(pidCriteria); parameters.add(pidConstraints); } else { // A = B sqlWHERE.append(" AND people.PersonIdentifier = ?"); description.append(" and a MIN equal to '" + pidCriteria + "'"); parameters.add(pidCriteria); } } if (single) { sqlWHERE.append(" AND people.PersonIdentifier = ?"); description.append(" and a MIN equal to '" + pidCriteria + "'"); parameters.add(pidCriteria); } } } if (searchCriteria.getGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR people.GUID = ?"); parameters.add(guid); } } if (guidWHERE.length() > 0) { // Append the guidWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" AND ("); // Append the guidWHERE but strip the first OR statement sqlWHERE.append(guidWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and has a GUID in the supplied list"); } } if (searchCriteria.getIdentifierList() != null) { final StringBuffer identifierWHERE = new StringBuffer(); for (String identifier : searchCriteria.getIdentifierList()) { if (StringUtils.isNotBlank(identifier)) { identifierWHERE.append(" OR people.PersonIdentifier = ?"); parameters.add(identifier); } } if (identifierWHERE.length() > 0) { // Append the identifierWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" AND ("); // Append the identifierWHERE but strip the first OR statement sqlWHERE.append(identifierWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and has a MIN number in the supplied list"); } } if (searchCriteria.getTitle() != null) { if (searchCriteria.getTitle().compareTo("") != 0) { sqlWHERE.append(" AND title.Name LIKE ?"); description.append(" and a title like '" + searchCriteria.getTitle() + "'"); parameters.add(searchCriteria.getTitle()); } } if (searchCriteria.getHonors() != null) { if (searchCriteria.getHonors().compareTo("") != 0) { sqlWHERE.append(" AND people.Honors LIKE ?"); description.append(" and honors like '" + searchCriteria.getHonors() + "'"); parameters.add("%" + searchCriteria.getHonors() + "%"); } } if (searchCriteria.getGender() != null) { if (searchCriteria.getGender().compareTo("") != 0) { // Only current supervisors sqlWHERE.append(" AND Gender LIKE ?"); description.append(" and a gender like '" + searchCriteria.getGender() + "'"); parameters.add(searchCriteria.getGender()); } } if (StringUtils.isNotBlank(searchCriteria.getTrainingStatus())) { sqlWHERE.append(" AND trainingstatus.Class LIKE ?"); description.append(" and a training status of '" + searchCriteria.getTrainingStatus() + "'"); parameters.add(searchCriteria.getTrainingStatus()); } if (StringUtils.isNotBlank(searchCriteria.getTrainingStatusDetail())) { sqlWHERE.append(" AND trainingstatus.Name LIKE ?"); description .append(" and a training status detail of '" + searchCriteria.getTrainingStatusDetail() + "'"); parameters.add(searchCriteria.getTrainingStatusDetail()); } // Process the membership parameters ArrayList<MembershipBean> memDetailsCriteria = (ArrayList<MembershipBean>) searchCriteria .getMembershipDetails(); ArrayList<MembershipBean> memDetailsContaints = (ArrayList<MembershipBean>) searchConstraints .getMembershipDetails(); for (int a = 0; a < memDetailsCriteria.size(); a++) { MembershipBean membershipCriteria = memDetailsCriteria.get(a); MembershipBean membershipConstraints = memDetailsContaints.get(a); Object[] result = null; final String className = membershipCriteria.getMembershipClass(); final String typeName = membershipCriteria.getMembershipType(); if (StringUtils.equalsIgnoreCase(className, "RACP") && StringUtils.equalsIgnoreCase(typeName, "")) { result = processRACPMembership(membershipCriteria, membershipConstraints); } if (StringUtils.equalsIgnoreCase(className, "RACP") && StringUtils.equalsIgnoreCase(typeName, "Fellowship Details")) { result = processRACPFellowship(membershipCriteria, membershipConstraints); } if (StringUtils.equalsIgnoreCase(className, "RACP") && StringUtils.equalsIgnoreCase(typeName, "Affiliation")) { result = processRACPAffiliation(membershipCriteria, membershipConstraints); } if (result != null) { String sql = (String) result[0]; String desc = (String) result[1]; Collection<Object> param = (Collection<Object>) result[2]; dataLogger.debug("Membership SQL: " + sql); // Build the membership sub-search if (StringUtils.isNotBlank(sql)) { sqlWHERE.append(" "); sqlWHERE.append(this.getSQL().getValue("person/searchMembership")); sqlWHERE.append(sql); sqlWHERE.append(")"); description.append(desc); // Append the class and type fields parameters.add(className); parameters.add(typeName); parameters.addAll(param); } } } /* Search for persons region */ if (searchCriteria.getRegion() != null) { if (searchCriteria.getRegion().compareTo("") != 0 && searchCriteria.getRegion().compareTo("Unknown?") != 0) { sqlWHERE.append(" AND region.Class LIKE ?"); description.append(" and is in the '" + searchCriteria.getRegion() + "' region"); parameters.add(searchCriteria.getRegion() + "%"); } } /* Get address */ if (searchCriteria.getFirstAddress() != null && searchConstraints.getFirstAddress() != null) { final AddressBean address = searchCriteria.getFirstAddress(); final AddressBean address2 = searchConstraints.getFirstAddress(); final StringBuffer addressSearch = new StringBuffer(); if (address.getPrimary() && address2.getPrimary()) { addressSearch.append(" AND address.PrimaryAddress = ?"); description.append(" is the preferred address"); parameters.add(true); } if (StringUtils.isNotBlank(address.getContactClass())) { addressSearch.append(" AND addresstype.Class LIKE ?"); description.append(" and has an address class of '" + address.getContactClass() + "'"); parameters.add(address.getContactClass()); } if (StringUtils.isNotBlank(address.getContactType()) && !StringUtils.equals(address.getContactType(), "Any")) { addressSearch.append(" AND addresstype.Name LIKE ?"); description.append(" and has an address type of '" + address.getContactType() + "'"); parameters.add(address.getContactType()); } if (StringUtils.isNotBlank(address.getCity())) { addressSearch.append(" AND address.City LIKE ?"); description.append(" and has an address in '" + address.getCity() + "' city"); parameters.add(address.getCity() + "%"); } if (StringUtils.isNotBlank(address.getState())) { addressSearch.append(" AND loc_state.Name LIKE ?"); description.append(" and has an address in the state of '" + address.getState() + "'"); parameters.add(address.getState() + "%"); } if (StringUtils.isNotBlank(address.getCountry())) { addressSearch.append(" AND loc_state.Class LIKE ?"); description.append(" and has an address in '" + address.getCountry() + "'"); parameters.add(address.getCountry() + "%"); } if (StringUtils.isNotBlank(address.getCountryAbbreviation())) { addressSearch.append(" AND loc_state.Abbreviation LIKE ?"); description.append(" and has an address in '" + address.getCountryAbbreviation() + "'"); parameters.add(address.getCountryAbbreviation()); } if (address.getReturnedMail() && address2.getReturnedMail()) { // Only returned mail addressSearch.append(" AND address.ReturnedMail = true"); description.append(" and has an address with returned mail"); } if (!address.getReturnedMail() && !address2.getReturnedMail()) { // Only non-returned mail addressSearch.append(" AND address.ReturnedMail = false"); description.append(" and has an address without returned mail"); } if (address.getRequestNoMail() && address2.getRequestNoMail()) { // Only those who have requested no mail addressSearch.append(" AND address.RequestNoMail = true"); description.append(" and has an address which has requested no mail"); } if (!address.getRequestNoMail() && !address2.getRequestNoMail()) { // Only those who have requested mail addressSearch.append(" AND address.RequestNoMail = false"); description.append(" and has an address which accepts mail"); } if (addressSearch.length() > 0) { sqlWHERE.append(" " + getSQL().getValue("person/searchAddress") + addressSearch.toString() + ")"); } } // Perform an email search if (searchCriteria.getFirstEmailAddress() != null && searchConstraints.getFirstEmailAddress() != null) { final EmailBean email = searchCriteria.getFirstEmailAddress(); final EmailBean email2 = searchConstraints.getFirstEmailAddress(); final StringBuffer emailSearch = new StringBuffer(); if (email.getPrimary() && email2.getPrimary()) { emailSearch.append(" AND email.PrimaryEmail = ?"); description.append(" is the preferred email address"); parameters.add(true); } if (StringUtils.isNotBlank(email.getContactType())) { emailSearch.append(" AND emailtype.Name LIKE ?"); description.append(" and has an email address type of '" + email.getContactType() + "'"); parameters.add(email.getContactType()); } if (email.getReturnedMail() && email2.getReturnedMail()) { // Only returned mail emailSearch.append(" AND email.ReturnedMail = true"); description.append(" and has an email address with returned mail"); } if (!email.getReturnedMail() && !email2.getReturnedMail()) { // Only non-returned mail emailSearch.append(" AND email.ReturnedMail = false"); description.append(" and has an email address without returned mail"); } if (email.getRequestNoMail() && email2.getRequestNoMail()) { // Only those who have requested no mail emailSearch.append(" AND email.RequestNoMail = true"); description.append(" and has an email address which has requested no mail"); } if (!email.getRequestNoMail() && !email2.getRequestNoMail()) { // Only those who have requested mail emailSearch.append(" AND email.RequestNoMail = false"); description.append(" and has an email address which accepts mail"); } if (email.getEmailQuestions() && email2.getEmailQuestions()) { // Get only EmailQuestions people emailSearch.append(" AND email.EmailQuestions = true"); description.append(" and wishes to recieve email questions"); } if (!email.getEmailQuestions() && !email2.getEmailQuestions()) { // Get only no EmailQuestions people emailSearch.append(" AND email.EmailQuestions = false"); description.append(" and does not wish to recieve email questions"); } if (StringUtils.isNotBlank(email.getEmail())) { // Do a search for the email address emailSearch.append(" AND email.Email = ?"); description.append(" and has an email address of '" + email.getEmail() + "'"); parameters.add(email.getEmail()); } if (emailSearch.length() > 0) { sqlWHERE.append(" " + getSQL().getValue("person/searchEmail") + emailSearch.toString() + ")"); } } // Check outstanding balances if (searchCriteria.getFinancialSummary() != null) { // Check if an identifier is set - if not do not bother searching. if (searchCriteria.getFinancialSummary().getId() > 0) { final StringBuffer financialSummarySearch = new StringBuffer(); final double closingBalanceA = searchCriteria.getFinancialSummary().getClosingBalance(); if (searchConstraints.getFinancialSummary() != null) { final double closingBalanceB = searchConstraints.getFinancialSummary().getClosingBalance(); financialSummarySearch.append(" WHERE searchindex.IndexType LIKE ?"); parameters.add("Current Balance"); if (closingBalanceA == closingBalanceB) { financialSummarySearch.append(" AND searchindex.CurrencyValue = ?"); description.append( " and has a current balance of '" + Formatter.toCurrency(closingBalanceA) + "'"); parameters.add(closingBalanceA); } if (closingBalanceA < closingBalanceB) { financialSummarySearch.append(" AND searchindex.CurrencyValue " + "BETWEEN ? AND ?"); description.append( " and has a current balance between '" + Formatter.toCurrency(closingBalanceA) + "' and '" + Formatter.toCurrency(closingBalanceB) + "'"); parameters.add(closingBalanceA); parameters.add(closingBalanceB); } if (closingBalanceA > closingBalanceB) { financialSummarySearch.append(" AND searchindex.CurrencyValue " + "BETWEEN ? AND ?"); description.append( " and has a current balance between '" + Formatter.toCurrency(closingBalanceB) + "' and '" + Formatter.toCurrency(closingBalanceA) + "'"); parameters.add(closingBalanceB); parameters.add(closingBalanceA); } } else { financialSummarySearch.append(" AND searchindex.CurrencyValue = ?"); description.append( " and has a current balance of '" + Formatter.toCurrency(closingBalanceA) + "'"); parameters.add(closingBalanceA); } sqlWHERE.append( " " + getSQL().getValue("person/searchBalance") + financialSummarySearch.toString() + ")"); } } // Do a search for organisations if the TreeMap exists if (searchCriteria.getEmployers() != null) { StringBuffer organisationSearch = new StringBuffer(); for (String index : searchCriteria.getEmployers().keySet()) { ItemBean employer = searchCriteria.getEmployers().get(index); if (organisationSearch.length() > 0) { organisationSearch.append(" OR "); } organisationSearch.append("organisation.Name = ?"); description.append(" and has been employed by '" + employer.getName() + "'"); parameters.add(employer.getName()); } if (organisationSearch.length() > 0) { sqlWHERE.append( this.getSQL().getValue("person/searchWorkplace") + " AND (" + organisationSearch + "))"); } } if (searchCriteria.getWorkshops() != null) { StringBuffer workshopSearch = new StringBuffer(); StringBuffer noWorkshopSearch = new StringBuffer(); for (WorkshopBean workshop : searchCriteria.getWorkshops()) { if (workshop.getType() != null) { if (workshop.getType().compareTo("") != 0) { workshopSearch.append(" AND workshoptype.Class = ?"); description.append(" and has been to a '" + workshop.getType() + "' workshop"); parameters.add(workshop.getType()); } } if (workshop.getWorkshopDate() != null) { Date workshopDate = workshop.getWorkshopDate(); Date workshop2Date = null; if (searchConstraints.getWorkshops() != null) { for (WorkshopBean workshop2 : searchConstraints.getWorkshops()) { workshop2Date = workshop2.getWorkshopDate(); } } if (workshop2Date != null) { String fieldA = this.getDf().format(workshopDate); String fieldB = this.getDf().format(workshop2Date); int larger = workshopDate.compareTo(workshop2Date); if (larger > 0) { if (workshop.getMemo().compareTo("Did not attend:") == 0) { // People without workshops or outside of the time workshopSearch.append(" AND (workshop.Date NOT BETWEEN ? AND ? "); workshopSearch.append("OR workshop.Date IS NULL)"); description.append(" and has not been to a workshop between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } else { // Workshop date after Workshop2 date workshopSearch.append(" AND workshop.Date BETWEEN ? AND ?"); description.append(" and has been to a workshop between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } } if (larger < 0) { if (workshop.getMemo().compareTo("Did not attend:") == 0) { // People without workshops or outside of the time workshopSearch.append(" AND (workshop.Date NOT BETWEEN ? AND ? "); workshopSearch.append("OR workshop.Date IS NULL)"); description.append(" and has not been to a workshop between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } else { // Workshop date before Workshop2 date workshopSearch.append(" AND workshop.Date BETWEEN ? AND ?"); description.append(" and has been to a workshop between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } } if (larger == 0) { if (workshop.getMemo().compareTo("Did not attend:") == 0) { // Workshop not on the date specified String field = this.getDf().format(workshop.getWorkshopDate()); workshopSearch.append(" AND (workshop.Date IS NULL OR " + "workshop.Date != ?)"); description.append(" and has not been to a workshop on '" + field + "'"); parameters.add(field); } else { // Workshop and Workshop2 are equal String field = this.getDf().format(workshop.getWorkshopDate()); workshopSearch.append(" AND workshop.Date = ?"); description.append(" and has been to a workshop on '" + field + "'"); parameters.add(field); } } } else { if (workshop.getMemo() != null) { if (workshop.getMemo().compareTo("Did not attend:") == 0) { // Workshop Date on the date specified String field = this.getDf().format(workshop.getWorkshopDate()); workshopSearch.append(" AND (workshop.Date IS NULL " + "OR workshop.Date != ?)"); description.append(" and has not been to a workshop on '" + field + "'"); parameters.add(field); } else { // Workshop Date on the date specified String field = this.getDf().format(workshop.getWorkshopDate()); workshopSearch.append(" AND workshop.Date = ?"); description.append(" and has been to a workshop on '" + field + "'"); parameters.add(field); } } } } if (workshop.getMemo() != null) { if (workshop.getMemo().compareTo("Has attended any") == 0) { noWorkshopSearch.append(" AND workshop.Date IS NOT NULL"); description.append(" and has attended any workshop"); } if (workshop.getMemo().compareTo("Has never attended any") == 0) { noWorkshopSearch.append(" AND workshop.Date IS NULL"); description.append(" and has never attended any workshops"); } } } if (workshopSearch.length() > 0) { sqlWHERE.append( " " + this.getSQL().getValue("person/searchWorkshop") + workshopSearch.toString() + ")"); } if (noWorkshopSearch.length() > 0) { sqlWHERE.append(" " + this.getSQL().getValue("person/searchNoWorkshop") + noWorkshopSearch.toString() + ")"); } } if (searchCriteria.getExams() != null) { StringBuffer examSearch = new StringBuffer(); for (ExamBean examCriteria : searchCriteria.getExams()) { if (examCriteria.getType() != null) { if (examCriteria.getType().compareTo("") != 0) { examSearch.append(" AND examtype.Class = ?"); description .append(" and has or is intending to undertake a '" + examCriteria.getType() + "'"); parameters.add(examCriteria.getType()); } } if (examCriteria.getStatus() != null) { if (examCriteria.getStatus().compareTo("") != 0) { examSearch.append(" AND examstatus.Class = ?"); description.append(" and the person '" + examCriteria.getStatus() + "' their exam"); parameters.add(examCriteria.getStatus()); } } if (examCriteria.getStatusLevel() != null) { if (examCriteria.getStatusLevel().compareTo("") != 0) { examSearch.append(" AND examstatus.Name = ?"); description.append( " and their exam fell within the '" + examCriteria.getStatusLevel() + "' band"); parameters.add(examCriteria.getStatusLevel()); } } if (examCriteria.getDateSat() != null) { Date examCriteriaDate = examCriteria.getDateSat(); Date examConstraintDate = null; if (searchConstraints.getExams() != null) { for (ExamBean examConstraint : searchConstraints.getExams()) { examConstraintDate = examConstraint.getDateSat(); } } if (examConstraintDate != null) { int larger = examCriteriaDate.compareTo(examConstraintDate); if (larger > 0) { // Exam Criteria date after Exam Constraint date String fieldA = this.getDf().format(examCriteriaDate); String fieldB = this.getDf().format(examConstraintDate); examSearch.append(" AND exam.DateSat BETWEEN ? AND ?"); description.append(" and sat an exam between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // Exam Criteria date before Exam Constraint date String fieldA = this.getDf().format(examCriteriaDate); String fieldB = this.getDf().format(examConstraintDate); examSearch.append(" AND exam.DateSat BETWEEN ? AND ?"); description.append(" and sat an exam between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // Exam on the date specified String field = this.getDf().format(examCriteriaDate); examSearch.append(" AND exam.DateSat = ?"); description.append("and sat an exam on '" + field + "'"); parameters.add(field); } } else { // Exam on the date specified String field = this.getDf().format(examCriteriaDate); examSearch.append(" AND exam.DateSat = ?"); description.append("and sat an exam on '" + field + "'"); parameters.add(field); } } } if (examSearch.length() > 0) { sqlWHERE.append(" " + this.getSQL().getValue("person/searchExam") + examSearch.toString() + ")"); } } if (searchCriteria.getQualifications() != null) { // Perform a qualification search StringBuffer qualificationSearch = new StringBuffer(); for (QualificationBean qualification : searchCriteria.getQualifications()) { if (qualification.getQualificationType() != null) { if (qualification.getQualificationType().compareTo("") != 0) { qualificationSearch.append(" AND qualificationtype.Class = ?"); description .append(" and has a '" + qualification.getQualificationType() + "' qualification"); parameters.add(qualification.getQualificationType()); } } if (qualification.getQualificationSubType() != null) { if (qualification.getQualificationSubType().compareTo("") != 0) { qualificationSearch.append(" AND qualificationtype.Name = ?"); description.append(" and has a qualification type of '" + qualification.getQualificationSubType() + "'"); parameters.add(qualification.getQualificationSubType()); } } if (qualification.getInstitution() != null) { if (qualification.getInstitution().compareTo("") != 0) { qualificationSearch.append(" AND qualification.Institution LIKE ?"); description.append( " and the qualification was awarded by '" + qualification.getInstitution() + "'"); parameters.add("%" + qualification.getInstitution() + "%"); } } if (qualification.getCountry() != null) { if (qualification.getCountry().compareTo("") != 0) { qualificationSearch.append(" AND qualification.Country LIKE ?"); description.append( " and the qualification was awarded in '" + qualification.getCountry() + "'"); parameters.add(qualification.getCountry() + "%"); } } if (qualification.getYear() > 0) { int qualificationCriteriaYear = qualification.getYear(); int qualificationConstraintYear = 0; if (searchConstraints.getQualifications() != null) { for (QualificationBean qualification2 : searchConstraints.getQualifications()) { qualificationConstraintYear = qualification2.getYear(); } } if (qualificationConstraintYear > 0) { if (qualificationConstraintYear > qualificationCriteriaYear) { // Qualification Criteria date after Qualification // Constraint date qualificationSearch.append(" AND qualification.Year BETWEEN ? AND ?"); description.append(" and the qualification was attained " + "between '" + qualificationCriteriaYear + "' and '" + qualificationConstraintYear + "'"); parameters.add(qualificationCriteriaYear); parameters.add(qualificationConstraintYear); } if (qualificationConstraintYear < qualificationCriteriaYear) { // Qualification Criteria date before Qualification // Constraint date qualificationSearch.append(" AND qualification.Year BETWEEN ? AND ?"); description.append(" and the qualification was attained " + "between '" + qualificationCriteriaYear + "' and '" + qualificationConstraintYear + "'"); parameters.add(qualificationConstraintYear); parameters.add(qualificationCriteriaYear); } if (qualificationConstraintYear == qualificationCriteriaYear) { // Qualification on the year specified qualificationSearch.append(" AND qualification.Year = ?"); description.append( "and qualification was attained on '" + qualificationCriteriaYear + "'"); parameters.add(qualificationCriteriaYear); } } else { // Exam on the date specified qualificationSearch.append(" AND qualification.Year = ?"); description.append( "and the qualification was attained on '" + qualificationCriteriaYear + "'"); parameters.add(qualificationCriteriaYear); } } } if (qualificationSearch.length() > 0) { sqlWHERE.append(" " + this.getSQL().getValue("person/searchQualification") + qualificationSearch.toString() + ")"); } } // Perform accreditation search if (searchCriteria.getTrainingSummary("Search") != null) { for (String index : searchCriteria.getTrainingSummary("Search").keySet()) { AccreditationBean[] details = searchCriteria.getTrainingSummary("Search").get(index); AccreditationBean accredA = null; AccreditationBean accredB = null; try { accredA = details[0]; } catch (Exception e) { dataLogger.error("Error casting summary (accredA): " + e.getMessage()); } try { accredB = details[1]; } catch (Exception e) { dataLogger.error("Error casting summary (accredB): " + e.getMessage()); } if (accredA != null && accredB != null) { StringBuffer accreditationSearch = new StringBuffer(); if (StringUtils.isNotBlank(accredA.getAbbreviation())) { description.append(" and has an accreditation type of '" + accredA.getAbbreviation() + "'"); parameters.add(accredA.getAbbreviation()); } else { parameters.add(""); } String searchIndex1 = " AND searchindex.ObjectTypeId1 = 0"; if (StringUtils.isNotBlank(accredA.getAccreditationClass())) { searchIndex1 = " AND searchtype1.Class = ?"; description.append( " and has an accreditation division of '" + accredA.getAccreditationClass() + "'"); parameters.add(accredA.getAccreditationClass()); } String searchIndex2 = " AND searchindex.ObjectTypeId2 = 0"; if (StringUtils.isNotBlank(accredA.getSpecialtyType())) { searchIndex2 = " AND searchtype2.Class = ?"; description .append(" and has an accreditation type of '" + accredA.getSpecialtyType() + "'"); parameters.add(accredA.getSpecialtyType()); } if (accredA.getWeeksCertified() == accredB.getWeeksCertified()) { // Equal to accreditationSearch.append(" WHERE (searchindex.IndexType = ? " + searchIndex1 + searchIndex2 + " AND searchindex.NumericValue = ?)"); description .append(" and has been accredited for " + accredA.getWeeksCertified() + " weeks"); parameters.add(accredA.getWeeksCertified()); } else { // Range accreditationSearch.append(" WHERE (searchindex.IndexType = ? " + searchIndex1 + searchIndex2 + " AND searchindex.NumericValue BETWEEN ? AND ?)"); description.append(" and has been accredited between " + accredA.getWeeksCertified() + " and " + accredB.getWeeksCertified() + " weeks"); parameters.add(accredA.getWeeksCertified()); parameters.add(accredB.getWeeksCertified()); } if (accreditationSearch.length() > 0) { sqlWHERE.append(" " + getSQL().getValue("person/searchAccreditation") + accreditationSearch.toString() + ")"); } } } } if (searchCriteria.getRotations() != null) { HashMap<Integer, Integer> guids = new HashMap<Integer, Integer>(); for (RotationBean rotation : searchCriteria.getRotations()) { if (rotation.getGUID() > 0) { try { RotationBean loaded = this.rotationDAO.loadGUID(rotation.getGUID()); guids.put(loaded.getPersonId(), 0); if (loaded.getSupervisors() != null) { for (SupervisorBean sup : loaded.getSupervisors()) { if (sup != null && sup.getPersonGUID() > 0) { guids.put(sup.getPersonGUID(), 0); } } } } catch (WhichDoctorDaoException wde) { // Error loading rotation dataLogger.error("Error loading rotation: " + wde.getMessage()); } } } if (guids.size() > 0) { StringBuffer rotationWHERE = new StringBuffer(); for (Integer guid : guids.keySet()) { if (rotationWHERE.length() > 0) { rotationWHERE.append(" OR "); } rotationWHERE.append("people.GUID = ?"); parameters.add(guid); } sqlWHERE.append(" AND ("); sqlWHERE.append(rotationWHERE.toString()); sqlWHERE.append(")"); description.append(" and was associated with a rotation"); } } // Perform a specialty search if (searchCriteria.getSpecialtyList() != null) { StringBuffer specialtySearch = new StringBuffer(); for (SpecialtyBean specialty : searchCriteria.getSpecialtyList()) { if (StringUtils.isNotBlank(specialty.getTrainingOrganisation())) { specialtySearch.append(" AND trainingprogram.Class = ?"); description.append(" and is training, or has trained, for a " + "specialty organised by the '" + specialty.getTrainingOrganisation() + "'"); parameters.add(specialty.getTrainingOrganisation()); } if (StringUtils.isNotBlank(specialty.getTrainingProgram())) { specialtySearch.append(" AND trainingprogram.Name = ?"); description.append(" and is training, or has trained, in the '" + specialty.getTrainingProgram() + "' specialty"); parameters.add(specialty.getTrainingProgram()); } if (specialty.getTrainingProgramYear() > 0) { int trainingProgramYearA = specialty.getTrainingProgramYear(); int trainingProgramYearB = 0; for (SpecialtyBean spConstnt : searchConstraints.getSpecialtyList()) { trainingProgramYearB = spConstnt.getTrainingProgramYear(); } if (trainingProgramYearB > 0) { if (trainingProgramYearB < trainingProgramYearA) { // Switch the two variables so that the criteria is smaller trainingProgramYearA = trainingProgramYearB; trainingProgramYearB = specialty.getTrainingProgramYear(); } specialtySearch.append(" AND specialty.TrainingProgramYear " + "BETWEEN ? AND ?"); description.append(" and a specialty with a curriculum year " + "between " + trainingProgramYearA + " and " + trainingProgramYearB); parameters.add(trainingProgramYearA); parameters.add(trainingProgramYearB); } else { specialtySearch.append(" AND specialty.TrainingProgramYear = ?"); description.append(" and a specialty with a curriculum year of " + trainingProgramYearA); parameters.add(trainingProgramYearA); } } if (StringUtils.isNotBlank(specialty.getStatus())) { specialtySearch.append(" AND specialtystatus.Class = ?"); description.append(" and has a specialty status of '" + specialty.getStatus() + "'"); parameters.add(specialty.getStatus()); } } if (specialtySearch.length() > 0) { sqlWHERE.append( " " + getSQL().getValue("person/searchSpecialty") + specialtySearch.toString() + ")"); } } // Other searches: cancelled, date issued if (searchCriteria.getCreatedDate() != null) { if (searchConstraints.getCreatedDate() != null) { int larger = searchCriteria.getCreatedDate().compareTo(searchConstraints.getCreatedDate()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getCreatedDate()); String fieldB = this.getDf().format(searchConstraints.getCreatedDate()); description.append(" and was created between '" + fieldB + "' and '" + fieldA + "'"); sqlWHERE.append(" AND guid.CreatedDate BETWEEN ? AND ?"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getCreatedDate()); String fieldB = this.getDf().format(searchConstraints.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate BETWEEN ? AND ?"); description.append(" and was created between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate = ?"); description.append(" and was created on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getCreatedDate()); sqlWHERE.append(" AND guid.CreatedDate = ?"); description.append(" and was created on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getModifiedDate() != null) { if (searchConstraints.getModifiedDate() != null) { int larger = searchCriteria.getModifiedDate().compareTo(searchConstraints.getModifiedDate()); if (larger > 0) { // SearchCriteria date after SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getModifiedDate()); String fieldB = this.getDf().format(searchConstraints.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate BETWEEN ? AND ?"); description.append(" and was modified between '" + fieldB + "' and '" + fieldA + "'"); parameters.add(fieldB); parameters.add(fieldA); } if (larger < 0) { // SearchCriteria date before SearchConstraint date String fieldA = this.getDf().format(searchCriteria.getModifiedDate()); String fieldB = this.getDf().format(searchConstraints.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate BETWEEN ? AND ?"); description.append(" and was modified between '" + fieldA + "' and '" + fieldB + "'"); parameters.add(fieldA); parameters.add(fieldB); } if (larger == 0) { // SearchCritier and SearchConstraint are equal String field = this.getDf().format(searchCriteria.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate = ?"); description.append(" and was modified on '" + field + "'"); parameters.add(field); } } else { String field = this.getDf().format(searchCriteria.getModifiedDate()); sqlWHERE.append(" AND guid.ModifiedDate = ?"); description.append(" and was modified on '" + field + "'"); parameters.add(field); } } if (searchCriteria.getIncludeGUIDList() != null) { final StringBuffer guidWHERE = new StringBuffer(); for (String guid : searchCriteria.getIncludeGUIDList()) { if (StringUtils.isNotBlank(guid)) { guidWHERE.append(" OR people.GUID = ?"); parameters.add(guid); } } if (guidWHERE.length() > 0) { // Append the guidWHERE buffer to the sqlWHERE buffer sqlWHERE.append(" OR ("); // Append the guidWHERE but strip the first OR statement sqlWHERE.append(guidWHERE.toString().substring(4)); sqlWHERE.append(")"); description.append(" and has a GUID in the supplied list"); } } String[] index = new String[] { sqlWHERE.toString(), DataFilter.getHtml(description.toString()) }; Map<String[], Collection<Object>> results = new HashMap<String[], Collection<Object>>(); results.put(index, parameters); return results; }
From source file:es.sm2.openppm.front.servlets.ProjectControlServlet.java
/** * Chart kpis/*from ww w . j a va 2s . co m*/ * * @param req * @param resp * @throws IOException */ private void kpiChartJX(HttpServletRequest req, HttpServletResponse resp) throws IOException { int idProject = ParamUtil.getInteger(req, "id"); PrintWriter out = resp.getWriter(); try { Date minDate = null; Date maxDate = null; SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy"); SimpleDateFormat tempDate = new SimpleDateFormat("MM/dd/yyyy"); Random random = new Random(); Float r = null; Float g = null; Float b = null; String[] defaultColors = new String[] { "#4bb2c5", "#c5b47f", "#EAA228", "#579575", "#839557", "#958c12", "#953579", "#4b5de4", "#d8b83f", "#ff5800", "#0085cc" }; Boolean insufficientDates = true; HistorickpiLogic historickpiLogic = new HistorickpiLogic(); ProjectLogic projectLogic = new ProjectLogic(getSettings(req), getResourceBundle(req)); JSONArray kpisValuesJSON = new JSONArray(); JSONArray kpisNamesJSON = new JSONArray(); JSONArray kpisColorsJSON = new JSONArray(); JSONObject updateJSON = new JSONObject(); List<String> joins = new ArrayList<String>(); joins.add(Projectkpi.METRICKPI); Project project = projectLogic.findById(idProject); ProjectKpiLogic projectKpiLogic = new ProjectKpiLogic(); List<Projectkpi> projectKpis = projectKpiLogic.findByRelation(Projectkpi.PROJECT, project, joins); //colors for (String defaultColor : defaultColors) { kpisColorsJSON.add(defaultColor); } int varianceColors = projectKpis.size() > defaultColors.length ? projectKpis.size() - defaultColors.length : 0; for (int i = 0; i < varianceColors; i++) { random.setSeed(new Date().getTime()); r = random.nextFloat(); g = random.nextFloat(); b = random.nextFloat(); Color randomColor = new Color(r, g, b); String rgb = Integer.toHexString(randomColor.getRGB()); rgb = rgb.substring(2, rgb.length()); rgb = StringPool.POUND.concat(rgb); kpisColorsJSON.add(rgb); } List<String> joinsHistoricKpi = new ArrayList<String>(); joinsHistoricKpi.add(Historickpi.EMPLOYEE); joinsHistoricKpi.add(Historickpi.EMPLOYEE + "." + Employee.CONTACT); for (Projectkpi kpi : projectKpis) { JSONArray kpiJSON = new JSONArray(); List<Historickpi> historic = historickpiLogic.findByRelation(Historickpi.PROJECTKPI, new Projectkpi(kpi.getIdProjectKpi()), Historickpi.ACTUALDATE, Constants.ASCENDENT, joinsHistoricKpi); if (!historic.isEmpty()) { String tempDateStr = tempDate.format(historic.get(0).getActualDate()); for (Historickpi hKpi : historic) { JSONArray hKpiJSON = new JSONArray(); hKpiJSON.add(date.format(hKpi.getActualDate())); hKpiJSON.add(hKpi.getValueKpi() == null ? 0 : hKpi.getValueKpi()); if (!tempDateStr.equals(date.format(hKpi.getActualDate()))) { insufficientDates = false; } kpiJSON.add(hKpiJSON); } } kpisValuesJSON.add(kpiJSON); if (kpi.getMetrickpi() != null) { kpisNamesJSON.add(kpi.getMetrickpi().getName()); } else { kpisNamesJSON.add(kpi.getSpecificKpi()); } /* min and max dates*/ if (!insufficientDates) { Date tempMinDate = historic.get(0).getActualDate(); Date tempMaxDate = historic.get(historic.size() - 1).getActualDate(); if (minDate == null && maxDate == null) { minDate = tempMinDate; maxDate = tempMaxDate; } else { if (tempMinDate.compareTo(minDate) < 0) { minDate = tempMinDate; } if (tempMaxDate.compareTo(maxDate) > 0) { maxDate = tempMaxDate; } } } } ChartJQPLOT chart = new ChartJQPLOT(minDate, maxDate); updateJSON.put("tickInterval", chart.getTickInterval()); updateJSON.put("minDate", chart.addDate(minDate, -1)); updateJSON.put("maxDate", chart.addDate(maxDate, 1)); updateJSON.put("kpisColors", kpisColorsJSON); updateJSON.put("kpisNames", kpisNamesJSON); updateJSON.put("kpisValues", kpisValuesJSON); updateJSON.put("insufficientDates", insufficientDates); out.print(updateJSON); } catch (Exception e) { ExceptionUtil.evalueExceptionJX(out, req, getResourceBundle(req), LOGGER, e); } finally { out.close(); } }
From source file:com.castis.xylophone.adsmadapter.convert.axistree.ConvertMgad.java
@SuppressWarnings("null") private void insertAdCampaigns(Ad_list allAdList, int deleteSchedulerLogId, InputDataType inputDataType, int feSyncNoticeboardId, ADSMSchedulerLogDTO categoryDataSchedulerLog, ResultAdsInfo result, PlacementOpportunityTypeEnum oppType, Platform platformType, InventoryType inventoryType) { int insertCampaignCount = 0; int totalCampaignCount = allAdList.getAdsList().size(); uniqueIdCheckInCampaign(allAdList, result, oppType, inventoryType); Map<String, List<Ads>> campaignMap = distributeADS(allAdList); Map<String, AccumulationGoiDay> adIdMap = new HashMap<String, AccumulationGoiDay>(); Map<Date, Integer> dateExposureMap = new HashMap<Date, Integer>(); Map<Date, Integer> dateMinimumExposureMap = new HashMap<Date, Integer>(); List<ADCampaignDailyExposure> adCampaignDailyExposureList = null; List<NonTargetUserGroup> nontargetUserList = new ArrayList<NonTargetUserGroup>(); List<CampaignTargetInfo> targetInfoList = new ArrayList<CampaignTargetInfo>(); Map<String, List<String>> targetInfoSet = new HashMap<String, List<String>>(); List<String> targetInfoStrList = new ArrayList<String>(); Integer adCampaignID = null;/*from w w w . j a v a 2 s . co m*/ Date updateDate = new Date(System.currentTimeMillis()); for (Map.Entry<String, List<Ads>> entry : campaignMap.entrySet()) { String externalId = entry.getKey(); List<Ads> value = entry.getValue(); try { //1. externalId ? ?? . for (Ads ads : value) { Integer reservePercent = CiStringUtil.parseInteger(ads.getReservePercent()); if (reservePercent == null) reservePercent = 0; if (ads.getStart_DT() != null && ads.getEnd_DT() != null && ads.getStart_DT().isEmpty() == false && ads.getEnd_DT().isEmpty() == false) { Date startDate = DateUtil.string2Date(ads.getStart_DT()); //yyyy-mm-dd Date endDate = DateUtil.string2Date(ads.getEnd_DT()); //yyyy-mm-dd AccumulationGoiDay accumulationGoiDay = new AccumulationGoiDay(ads.getGoi_CNT(), ads.getGoi_DAY(), CiDateUtil.countDayInLicense(ads.getStart_DT(), ads.getEnd_DT(), null), reservePercent, dailyMinimumExposureGuaranteeRate); if (ads.getAd_ID() != null && ads.getAd_ID().isEmpty() == false) { if (ads.getGoi_DAY() != null && ads.getGoi_DAY().isEmpty() == false) { Date nextDate = startDate; int dayCnt = 0; while (nextDate.compareTo(endDate) <= 0) { Integer dailyExposure = dateExposureMap.get(nextDate); if (dailyExposure == null) dailyExposure = 0; dateExposureMap.put(nextDate, dailyExposure += accumulationGoiDay.getAccumulationCounts()[dayCnt]); Integer dailyMinimumExposure = dateMinimumExposureMap.get(nextDate); if (dailyMinimumExposure == null) dailyMinimumExposure = 0; dateMinimumExposureMap.put(nextDate, dailyMinimumExposure += accumulationGoiDay .getDailyMinimumExposureCount()[dayCnt]); nextDate = DateUtil.getNextDate(nextDate); dayCnt++; } } } adIdMap.put(ads.getAd_ID(), accumulationGoiDay); } } //2. ?? Data ? adCampaignDailyExposureList = new ArrayList<ADCampaignDailyExposure>(); for (Map.Entry<Date, Integer> dateEntry : dateExposureMap.entrySet()) { Date date = dateEntry.getKey(); Integer exposure = dateEntry.getValue(); ADCampaignDailyExposure adCampaignDailyExposure = new ADCampaignDailyExposure( new ADCampaignDailyExposureKey(externalId, date, oppType, inventoryType), exposure, updateDate); adCampaignDailyExposureList.add(adCampaignDailyExposure); } } catch (Exception e) { log.error("ADSchedulerId (" + externalId + ") ? . ? : " + value.size() + ", err : " + e.getMessage()); insertCampaignCount += value.size(); for (Ads ads : value) { ResultFileUtil.addAdsInfoResult(ads, false, "100", e.getMessage(), inventoryType, oppType, result); campaignResult.increaseErrorCount(); } //?? ? ?? ?. continue; } //3. ?? try { inventoryExportSysCompForAdapter.insertADCampaignDailyExposureList(adCampaignDailyExposureList); } catch (Exception e) { log.error("ADSchedulerId (" + externalId + ") ? . ? : " + value.size() + ", err : " + e.getMessage()); insertCampaignCount += value.size(); for (Ads ads : value) { ResultFileUtil.addAdsInfoResult(ads, false, "30", e.getMessage(), inventoryType, oppType, result); campaignResult.increaseErrorCount(); } //?? ? ?? ?. continue; } //4. ? . for (Ads ads : value) { AccumulationGoiDay accumulationGoiDay = adIdMap.get(ads.getAd_ID()); if (ads.getAd_ID() != null && ads.getAd_ID().isEmpty() == false) { if (ads.getGoi_DAY() != null && ads.getGoi_DAY().isEmpty() == false) { if (ads.getStart_DT() != null && ads.getEnd_DT() != null && ads.getStart_DT().isEmpty() == false && ads.getEnd_DT().isEmpty() == false) { Date startDate = DateUtil.string2Date(ads.getStart_DT()); //yyyy-mm-dd Date endDate = DateUtil.string2Date(ads.getEnd_DT()); //yyyy-mm-dd accumulationGoiDay.replaceAccumulationGoi(dateExposureMap, dateMinimumExposureMap, startDate, endDate); } } } adCampaignID = generateADCampaign(ads, deleteSchedulerLogId, inputDataType, feSyncNoticeboardId, categoryDataSchedulerLog, result, oppType, accumulationGoiDay, inventoryType, platformType); insertCampaignCount++; //? mgad non_target_user_group ?? , (, ?) if (inventoryType == InventoryType.CUETONE && adCampaignID != null) { nontargetUserList.addAll(updateNonTargetUserGroup(adCampaignID, ads)); targetInfoList.addAll(updateTargetInfo(ads, targetInfoSet, targetInfoStrList)); } if ((insertCampaignCount % 1000) == 0) log.info(totalCampaignCount + " ? " + insertCampaignCount + " ?? ."); } //5. Map . dateExposureMap.clear(); dateMinimumExposureMap.clear(); adIdMap.clear(); } //?mgad : non_target_user_group, ? if (inventoryType == InventoryType.CUETONE) { inventoryExportSysCompForAdapter.deleteChannelTargetInfo(); inventoryExportSysCompForAdapter.saveChannelTargetInfo(targetInfoList); inventoryExportSysCompForAdapter.deleteNonTargetUserGroup(); inventoryExportSysCompForAdapter.insertNonTargetUserGroup(nontargetUserList); } }