Example usage for java.util LinkedHashMap values

List of usage examples for java.util LinkedHashMap values

Introduction

In this page you can find the example usage for java.util LinkedHashMap values.

Prototype

public Collection<V> values() 

Source Link

Document

Returns a Collection view of the values contained in this map.

Usage

From source file:org.finra.dm.service.helper.Hive13DdlGenerator.java

/**
 * Gets a list of Hive partitions. For single level partitioning, no auto-discovery of sub-partitions (sub-directories) is needed - the business object data
 * will be represented by a single Hive partition instance.  For multiple level partitioning, this method performs an auto-discovery of all sub-partitions
 * (sub-directories) and creates a Hive partition object instance for each partition.
 *
 * @param businessObjectDataKey the business object data key.
 * @param autoDiscoverableSubPartitionColumns the auto-discoverable sub-partition columns.
 * @param s3KeyPrefix the S3 key prefix.
 * @param storageFiles the storage files.
 * @param businessObjectDataEntity the business object data entity.
 * @param storageName the storage name./*from w ww .  java 2 s.  c o  m*/
 *
 * @return the list of Hive partitions
 */
public List<HivePartitionDto> getHivePartitions(BusinessObjectDataKey businessObjectDataKey,
        List<SchemaColumn> autoDiscoverableSubPartitionColumns, String s3KeyPrefix, List<String> storageFiles,
        BusinessObjectDataEntity businessObjectDataEntity, String storageName) {
    // We are using linked hash map to preserve the order of the discovered partitions.
    LinkedHashMap<List<String>, HivePartitionDto> linkedHashMap = new LinkedHashMap<>();

    Pattern pattern = getHivePathPattern(autoDiscoverableSubPartitionColumns);
    for (String storageFile : storageFiles) {
        // Remove S3 key prefix from the file path. Please note that the storage files are already validated to start with S3 key prefix.
        String relativeFilePath = storageFile.substring(s3KeyPrefix.length());

        // Try to match the relative file path to the expected subpartition folders.
        Matcher matcher = pattern.matcher(relativeFilePath);
        Assert.isTrue(matcher.matches(), String.format(
                "Registered storage file or directory does not match the expected Hive sub-directory pattern. "
                        + "Storage: {%s}, file/directory: {%s}, business object data: {%s}, S3 key prefix: {%s}, pattern: {^%s$}",
                storageName, storageFile,
                dmDaoHelper.businessObjectDataEntityAltKeyToString(businessObjectDataEntity), s3KeyPrefix,
                pattern.pattern()));

        // Add the top level partition value.
        HivePartitionDto newHivePartition = new HivePartitionDto();
        newHivePartition.getPartitionValues().add(businessObjectDataKey.getPartitionValue());
        newHivePartition.getPartitionValues().addAll(businessObjectDataKey.getSubPartitionValues());
        // Extract relative partition values.
        for (int i = 1; i <= matcher.groupCount(); i++) {
            newHivePartition.getPartitionValues().add(matcher.group(i));
        }

        // Remove the trailing "/" plus an optional file name from the file path and store the result string as this partition relative path.
        newHivePartition.setPath(relativeFilePath.replaceAll("/[^/]*$", ""));

        // Check if we already have that partition discovered - that would happen if partition contains multiple data files.
        HivePartitionDto hivePartition = linkedHashMap.get(newHivePartition.getPartitionValues());

        if (hivePartition != null) {
            // Partition is already discovered, so just validate that the relative file paths match.
            Assert.isTrue(hivePartition.getPath().equals(newHivePartition.getPath()), String.format(
                    "Found two different locations for the same Hive partition. Storage: {%s}, business object data: {%s}, "
                            + "S3 key prefix: {%s}, path[1]: {%s}, path[2]: {%s}",
                    storageName, dmDaoHelper.businessObjectDataEntityAltKeyToString(businessObjectDataEntity),
                    s3KeyPrefix, hivePartition.getPath(), newHivePartition.getPath()));
        } else {
            // Add this partition to the hash map of discovered partitions.
            linkedHashMap.put(newHivePartition.getPartitionValues(), newHivePartition);
        }
    }

    List<HivePartitionDto> hivePartitions = new ArrayList<>();
    hivePartitions.addAll(linkedHashMap.values());

    return hivePartitions;
}

From source file:oscar.dms.actions.DmsInboxManageAction.java

public ActionForward prepareForContentPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from   w  w w . ja v a  2  s .c o  m
    HttpSession session = request.getSession();
    try {
        if (session.getAttribute("userrole") == null)
            response.sendRedirect("../logout.jsp");
    } catch (Exception e) {
        logger.error("Error", e);
    }

    // can't use userrole from session, because it changes if provider A search for provider B's documents

    // oscar.oscarMDS.data.MDSResultsData mDSData = new oscar.oscarMDS.data.MDSResultsData();
    CommonLabResultData comLab = new CommonLabResultData();
    // String providerNo = request.getParameter("providerNo");
    String providerNo = (String) session.getAttribute("user");
    String searchProviderNo = request.getParameter("searchProviderNo");
    String ackStatus = request.getParameter("status");
    String demographicNo = request.getParameter("demographicNo"); // used when searching for labs by patient instead of provider
    String scannedDocStatus = request.getParameter("scannedDocument");
    Integer page = 0;
    try {
        page = Integer.parseInt(request.getParameter("page"));
        if (page > 0) {
            page--;
        }
    } catch (NumberFormatException nfe) {
        page = 0;
    }
    Integer pageSize = 20;
    try {
        String tmp = request.getParameter("pageSize");
        pageSize = Integer.parseInt(tmp);
    } catch (NumberFormatException nfe) {
        pageSize = 20;
    }
    scannedDocStatus = "I";

    String startDateStr = request.getParameter("startDate");
    String endDateStr = request.getParameter("endDate");

    String view = request.getParameter("view");
    if (view == null || "".equals(view)) {
        view = "all";
    }

    boolean mixLabsAndDocs = "normal".equals(view) || "all".equals(view);

    Date startDate = null;
    Date endDate = null;

    try {
        if (startDateStr != null && startDateStr.length() > 0) {
            startDateStr = startDateStr.trim();
            startDate = UtilDateUtilities.StringToDate(startDateStr);
        }
        if (endDateStr != null && endDateStr.length() > 0) {
            endDateStr = endDateStr.trim();
            endDate = UtilDateUtilities.StringToDate(endDateStr);
        }
    } catch (Exception e) {
        startDate = null;
        endDate = null;
    }

    Boolean isAbnormal = null;
    if ("abnormal".equals(view))
        isAbnormal = new Boolean(true);
    if ("normal".equals(view))
        isAbnormal = new Boolean(false);

    if (ackStatus == null) {
        ackStatus = "N";
    } // default to new labs only
    if (providerNo == null) {
        providerNo = "";
    }
    if (searchProviderNo == null) {
        searchProviderNo = providerNo;
    }
    String roleName = "";
    List<SecUserRole> roles = secUserRoleDao.getUserRoles(searchProviderNo);
    for (SecUserRole r : roles) {
        if (r != null) {
            if (roleName.length() == 0) {
                roleName = r.getRoleName();

            } else {
                roleName += "," + r.getRoleName();
            }
        }
    }
    roleName += "," + searchProviderNo;
    // mDSData.populateMDSResultsData2(searchProviderNo, demographicNo, request.getParameter("fname"), request.getParameter("lname"), request.getParameter("hnum"), ackStatus);
    // HashMap<String,String> docQueue=comLab.getDocumentQueueLinks();
    List<QueueDocumentLink> qd = queueDocumentLinkDAO.getQueueDocLinks();
    HashMap<String, String> docQueue = new HashMap();
    for (QueueDocumentLink qdl : qd) {
        Integer i = qdl.getDocId();
        Integer n = qdl.getQueueId();
        docQueue.put(i.toString(), n.toString());
    }

    InboxResultsDao inboxResultsDao = (InboxResultsDao) SpringUtils.getBean("inboxResultsDao");
    String patientFirstName = request.getParameter("fname");
    String patientLastName = request.getParameter("lname");
    String patientHealthNumber = request.getParameter("hnum");

    ArrayList<LabResultData> labdocs = new ArrayList<LabResultData>();

    if (!"labs".equals(view) && !"abnormal".equals(view)) {
        labdocs = inboxResultsDao.populateDocumentResultsData(searchProviderNo, demographicNo, patientFirstName,
                patientLastName, patientHealthNumber, ackStatus, true, page, pageSize, mixLabsAndDocs,
                isAbnormal);
    }
    if (!"documents".equals(view)) {
        labdocs.addAll(comLab.populateLabResultsData(searchProviderNo, demographicNo, patientFirstName,
                patientLastName, patientHealthNumber, ackStatus, scannedDocStatus, true, page, pageSize,
                mixLabsAndDocs, isAbnormal));
    }

    labdocs = (ArrayList<LabResultData>) filterLabDocsForSuperSite(labdocs, providerNo);

    ArrayList<LabResultData> validlabdocs = new ArrayList<LabResultData>();

    DocumentResultsDao documentResultsDao = (DocumentResultsDao) SpringUtils.getBean("documentResultsDao");
    // check privilege for documents only
    for (LabResultData data : labdocs) {
        if (data.isDocument()) {
            String docid = data.getSegmentID();

            String queueid = docQueue.get(docid);
            if (queueid != null) {
                queueid = queueid.trim();

                int queueIdInt = Integer.parseInt(queueid);

                // if doc sent to default queue and no valid provider, do NOT include it
                if (queueIdInt == Queue.DEFAULT_QUEUE_ID && !documentResultsDao.isSentToValidProvider(docid)
                        && isSegmentIDUnique(validlabdocs, data)) {
                    // validlabdocs.add(data);
                }
                // if doc sent to default queue && valid provider, check if it's sent to this provider, if yes include it
                else if (queueIdInt == Queue.DEFAULT_QUEUE_ID && documentResultsDao.isSentToValidProvider(docid)
                        && documentResultsDao.isSentToProvider(docid, searchProviderNo)
                        && isSegmentIDUnique(validlabdocs, data)) {
                    validlabdocs.add(data);
                }
                // if doc setn to non-default queue and valid provider, check if provider is in the queue or equal to the provider
                else if (queueIdInt != Queue.DEFAULT_QUEUE_ID
                        && documentResultsDao.isSentToValidProvider(docid)) {
                    Vector vec = OscarRoleObjectPrivilege.getPrivilegeProp("_queue." + queueid);
                    if (OscarRoleObjectPrivilege.checkPrivilege(roleName, (Properties) vec.get(0),
                            (Vector) vec.get(1))
                            || documentResultsDao.isSentToProvider(docid, searchProviderNo)) {
                        // labs is in provider's queue,do nothing
                        if (isSegmentIDUnique(validlabdocs, data)) {
                            validlabdocs.add(data);
                        }
                    }
                }
                // if doc sent to non default queue and no valid provider, check if provider is in the non default queue
                else if (!queueid.equals(Queue.DEFAULT_QUEUE_ID)
                        && !documentResultsDao.isSentToValidProvider(docid)) {
                    Vector vec = OscarRoleObjectPrivilege.getPrivilegeProp("_queue." + queueid);
                    if (OscarRoleObjectPrivilege.checkPrivilege(roleName, (Properties) vec.get(0),
                            (Vector) vec.get(1))) {
                        // labs is in provider's queue,do nothing
                        if (isSegmentIDUnique(validlabdocs, data)) {
                            validlabdocs.add(data);
                        }

                    }
                }
            }
        } else {// add lab
            if (isSegmentIDUnique(validlabdocs, data)) {
                validlabdocs.add(data);
            }
        }
    }

    // Find the oldest lab returned in labdocs, use that as the limit date for the HRM query
    Date oldestLab = null;
    Date newestLab = null;
    if (request.getParameter("newestDate") != null) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newestLab = formatter.parse(request.getParameter("newestDate"));
        } catch (Exception e) {
            logger.error("Couldn't parse date + " + request.getParameter("newestDate"), e);
        }
    }

    for (LabResultData result : labdocs) {
        if (result != null && result.getDateObj() != null) {
            if (oldestLab == null || oldestLab.compareTo(result.getDateObj()) > 0)
                oldestLab = result.getDateObj();
            if (request.getParameter("newestDate") != null
                    && (newestLab == null || newestLab.compareTo(result.getDateObj()) < 0))
                newestLab = result.getDateObj();
        }
    }

    HRMResultsData hrmResult = new HRMResultsData();

    Collection<LabResultData> hrmDocuments = hrmResult.populateHRMdocumentsResultsData(searchProviderNo,
            ackStatus, newestLab, oldestLab);
    if (oldestLab == null) {
        for (LabResultData hrmDocument : hrmDocuments) {
            if (oldestLab == null
                    || (hrmDocument.getDateObj() != null && oldestLab.compareTo(hrmDocument.getDateObj()) > 0))
                oldestLab = hrmDocument.getDateObj();
        }
    }

    //labdocs is already filtered for super site access.. not just filter hrmDocuments
    hrmDocuments = filterLabDocsForSuperSite(hrmDocuments, providerNo);

    labdocs.addAll(hrmDocuments);
    Collections.sort(labdocs);

    HashMap<String, LabResultData> labMap = new HashMap<String, LabResultData>();
    LinkedHashMap<String, ArrayList<String>> accessionMap = new LinkedHashMap<String, ArrayList<String>>();

    int accessionNumCount = 0;
    for (LabResultData result : labdocs) {
        if (startDate != null && startDate.after(result.getDateObj())) {
            continue;
        }

        if (endDate != null && endDate.before(result.getDateObj())) {
            continue;
        }

        String segmentId = result.getSegmentID();
        if (result.isDocument())
            segmentId += "d";
        else if (result.isHRM())
            segmentId += "h";

        labMap.put(segmentId, result);
        ArrayList<String> labNums = new ArrayList<String>();

        if (result.accessionNumber == null || result.accessionNumber.equals("")) {
            labNums.add(segmentId);
            accessionNumCount++;
            accessionMap.put("noAccessionNum" + accessionNumCount + result.labType, labNums);
        } else if (!accessionMap.containsKey(result.accessionNumber + result.labType)) {
            labNums.add(segmentId);
            accessionMap.put(result.accessionNumber + result.labType, labNums);

            // Different MDS Labs may have the same accession Number if they are seperated
            // by two years. So accession numbers are limited to matching only if their
            // labs are within one year of eachother
        } else {
            labNums = accessionMap.get(result.accessionNumber + result.labType);
            boolean matchFlag = false;
            for (int j = 0; j < labNums.size(); j++) {
                LabResultData matchingResult = labMap.get(labNums.get(j));

                Date dateA = result.getDateObj();
                Date dateB = matchingResult.getDateObj();
                int monthsBetween = 0;
                if (dateA == null || dateB == null) {
                    monthsBetween = 5;
                } else if (dateA.before(dateB)) {
                    monthsBetween = UtilDateUtilities.getNumMonths(dateA, dateB);
                } else {
                    monthsBetween = UtilDateUtilities.getNumMonths(dateB, dateA);
                }

                if (monthsBetween < 4) {
                    matchFlag = true;
                    break;
                }
            }
            if (!matchFlag) {
                labNums.add(segmentId);
                accessionMap.put(result.accessionNumber + result.labType, labNums);
            }
        }
    }

    labdocs.clear();

    for (ArrayList<String> labNums : accessionMap.values()) {
        // must sort through in reverse to keep the labs in the correct order
        for (int j = labNums.size() - 1; j >= 0; j--) {
            labdocs.add(labMap.get(labNums.get(j)));
        }
    }
    logger.debug("labdocs.size()=" + labdocs.size());

    /* find all data for the index.jsp page */
    Hashtable patientDocs = new Hashtable();
    Hashtable patientIdNames = new Hashtable();
    String patientIdNamesStr = "";
    Hashtable docStatus = new Hashtable();
    Hashtable docType = new Hashtable();
    Hashtable<String, List<String>> ab_NormalDoc = new Hashtable();

    for (int i = 0; i < labdocs.size(); i++) {
        LabResultData data = labdocs.get(i);

        List<String> segIDs = new ArrayList<String>();
        String labPatientId = data.getLabPatientId();
        if (labPatientId == null || labPatientId.equals("-1"))
            labPatientId = "-1";

        if (data.isAbnormal()) {
            List<String> abns = ab_NormalDoc.get("abnormal");
            if (abns == null) {
                abns = new ArrayList<String>();
                abns.add(data.getSegmentID());
            } else {
                abns.add(data.getSegmentID());
            }
            ab_NormalDoc.put("abnormal", abns);
        } else {
            List<String> ns = ab_NormalDoc.get("normal");
            if (ns == null) {
                ns = new ArrayList<String>();
                ns.add(data.getSegmentID());
            } else {
                ns.add(data.getSegmentID());
            }
            ab_NormalDoc.put("normal", ns);
        }
        if (patientDocs.containsKey(labPatientId)) {

            segIDs = (List) patientDocs.get(labPatientId);
            segIDs.add(data.getSegmentID());
            patientDocs.put(labPatientId, segIDs);
        } else {
            segIDs.add(data.getSegmentID());
            patientDocs.put(labPatientId, segIDs);
            patientIdNames.put(labPatientId, data.patientName);
            patientIdNamesStr += ";" + labPatientId + "=" + data.patientName;
        }
        docStatus.put(data.getSegmentID(), data.getAcknowledgedStatus());
        docType.put(data.getSegmentID(), data.labType);
    }

    Integer totalDocs = 0;
    Integer totalHL7 = 0;
    Hashtable<String, List<String>> typeDocLab = new Hashtable();
    Enumeration keys = docType.keys();
    while (keys.hasMoreElements()) {
        String keyDocLabId = ((String) keys.nextElement());
        String valType = (String) docType.get(keyDocLabId);

        if (valType.equalsIgnoreCase("DOC")) {
            if (typeDocLab.containsKey("DOC")) {
                List<String> docids = typeDocLab.get("DOC");
                docids.add(keyDocLabId);// add doc id to list
                typeDocLab.put("DOC", docids);
            } else {
                List<String> docids = new ArrayList<String>();
                docids.add(keyDocLabId);
                typeDocLab.put("DOC", docids);
            }
            totalDocs++;
        } else if (valType.equalsIgnoreCase("HL7")) {
            if (typeDocLab.containsKey("HL7")) {
                List<String> hl7ids = typeDocLab.get("HL7");
                hl7ids.add(keyDocLabId);
                typeDocLab.put("HL7", hl7ids);
            } else {
                List<String> hl7ids = new ArrayList<String>();
                hl7ids.add(keyDocLabId);
                typeDocLab.put("HL7", hl7ids);
            }
            totalHL7++;
        }
    }

    Hashtable patientNumDoc = new Hashtable();
    Enumeration patientIds = patientDocs.keys();
    String patientIdStr = "";
    Integer totalNumDocs = 0;
    while (patientIds.hasMoreElements()) {
        String key = (String) patientIds.nextElement();
        patientIdStr += key;
        patientIdStr += ",";
        List<String> val = (List<String>) patientDocs.get(key);
        Integer numDoc = val.size();
        patientNumDoc.put(key, numDoc);
        totalNumDocs += numDoc;
    }

    List<String> normals = ab_NormalDoc.get("normal");
    List<String> abnormals = ab_NormalDoc.get("abnormal");

    logger.debug("labdocs.size()=" + labdocs.size());

    // set attributes
    request.setAttribute("pageNum", page);
    request.setAttribute("docType", docType);
    request.setAttribute("patientDocs", patientDocs);
    request.setAttribute("providerNo", providerNo);
    request.setAttribute("searchProviderNo", searchProviderNo);
    request.setAttribute("patientIdNames", patientIdNames);
    request.setAttribute("docStatus", docStatus);
    request.setAttribute("patientIdStr", patientIdStr);
    request.setAttribute("typeDocLab", typeDocLab);
    request.setAttribute("demographicNo", demographicNo);
    request.setAttribute("ackStatus", ackStatus);
    request.setAttribute("labdocs", labdocs);
    request.setAttribute("patientNumDoc", patientNumDoc);
    request.setAttribute("totalDocs", totalDocs);
    request.setAttribute("totalHL7", totalHL7);
    request.setAttribute("normals", normals);
    request.setAttribute("abnormals", abnormals);
    request.setAttribute("totalNumDocs", totalNumDocs);
    request.setAttribute("patientIdNamesStr", patientIdNamesStr);
    request.setAttribute("oldestLab",
            oldestLab != null ? DateUtils.formatDate(oldestLab, "yyyy-MM-dd HH:mm:ss") : null);

    return mapping.findForward("dms_page");
}

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

@SuppressWarnings("unchecked")
private List<ImportantTerm> getImportantTerms(FullTextQuery fullTextQuery, int count, boolean filterStopWords) {
    final Long start = System.currentTimeMillis();
    final List<Object[]> results = fullTextQuery.list();
    final LinkedHashMap<String, Tuple<Integer, Float>> termCountMap = new LinkedHashMap<String, Tuple<Integer, Float>>();

    final FullTextSession fullTextSession = Search.getFullTextSession((Session) this.em.getDelegate());
    final SearchFactory searchFactory = fullTextSession.getSearchFactory();
    final IndexReaderAccessor ira = searchFactory.getIndexReaderAccessor();
    final IndexReader reader = ira.open(com.mothsoft.alexis.domain.Document.class);
    final IndexSearcher searcher = new IndexSearcher(reader);

    final List<ImportantTerm> importantTerms;
    final int numDocs;
    try {/* w w  w .java  2s  .c  o m*/
        numDocs = reader.numDocs();
        Term luceneTerm = new Term(CONTENT_TEXT_FIELD_NAME);

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Found %d matching Lucene documents of %d in reader", results.size(),
                    numDocs));
        }

        // loop over all the matching documents
        for (final Object[] ith : results) {
            int docId = ((Number) ith[0]).intValue();
            final TermFreqVector tfv = reader.getTermFreqVector(docId, CONTENT_TEXT_FIELD_NAME);

            if (tfv == null) {
                continue;
            }

            final String[] terms = tfv.getTerms();
            final int[] freqs = tfv.getTermFrequencies();

            // total document size
            int size = 0;

            for (int freq : freqs) {
                size += freq;
            }

            if (logger.isDebugEnabled()) {
                logger.debug(
                        String.format("Lucene document %d has %d terms, to be merged with running count %d",
                                docId, size, termCountMap.size()));
            }

            // loop over the terms and aggregate the counts and tf-idf
            int i = 0;
            for (final String term : terms) {
                if (StopWords.ENGLISH.contains(term)) {
                    continue;
                }

                luceneTerm = luceneTerm.createTerm(term);
                final int termCount = freqs[i++];

                final Tuple<Integer, Float> countScore;
                if (termCountMap.containsKey(term)) {
                    countScore = termCountMap.get(term);
                    countScore.t1 += termCount;
                    countScore.t2 += (TFIDF.score(term, termCount, size, numDocs,
                            searcher.docFreq(luceneTerm)));
                } else {
                    countScore = new Tuple<Integer, Float>();
                    countScore.t1 = termCount;
                    countScore.t2 = (TFIDF.score(term, termCount, size, numDocs, searcher.docFreq(luceneTerm)));
                    termCountMap.put(term, countScore);
                }
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Completed Lucene document processing.");
        }

        importantTerms = new ArrayList<ImportantTerm>(termCountMap.size());

        // find max TF-IDF
        float maxTfIdf = 0.0f;
        for (final Tuple<Integer, Float> ith : termCountMap.values()) {
            if (ith.t2 > maxTfIdf) {
                maxTfIdf = ith.t2;
            }
        }

        for (final Map.Entry<String, Tuple<Integer, Float>> entry : termCountMap.entrySet()) {
            final int ithCount = entry.getValue().t1;
            final float ithTfIdf = entry.getValue().t2;
            importantTerms.add(new ImportantTerm(entry.getKey(), ithCount, ithTfIdf, maxTfIdf));
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Completed term aggregation, will clear term map");
        }

        termCountMap.clear();

    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            searcher.close();
        } catch (IOException e) {
            logger.warn("Failed to close searcher: " + e, e);
        }
        ira.close(reader);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Sorting terms");
    }

    Collections.sort(importantTerms, new Comparator<ImportantTerm>() {
        @Override
        public int compare(ImportantTerm term1, ImportantTerm term2) {
            return -1 * term1.getTfIdf().compareTo(term2.getTfIdf());
        }
    });

    if (logger.isDebugEnabled()) {
        logger.debug("Term sort complete");
    }

    if (importantTerms.isEmpty() || importantTerms.size() < count) {
        if (logger.isDebugEnabled()) {
            logger.debug("Will return full list.");
        }
        logger.debug("Timer: " + (System.currentTimeMillis() - start));
        return importantTerms;
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Will return sublist containing " + count + " of " + importantTerms.size() + " terms.");
        }

        logger.debug("Timer: " + (System.currentTimeMillis() - start));
        return importantTerms.subList(0, count);
    }
}

From source file:org.apache.asterix.translator.LangExpressionToPlanTranslator.java

/**
 * Eliminate shared operator references in a query plan rooted at <code>currentOpRef.getValue()</code>.
 * Deep copy a new query plan subtree whenever there is a shared operator reference.
 *
 * @param currentOpRef,/*w w w  .java2 s.  co m*/
 *            the operator reference to consider
 * @param opRefSet,
 *            the set storing seen operator references so far.
 * @return a mapping that maps old variables to new variables, for the ancestors of
 *         <code>currentOpRef</code> to replace variables properly.
 * @throws AsterixException
 */
private LinkedHashMap<LogicalVariable, LogicalVariable> eliminateSharedOperatorReference(
        Mutable<ILogicalOperator> currentOpRef, Set<Mutable<ILogicalOperator>> opRefSet)
        throws AsterixException {
    try {
        opRefSet.add(currentOpRef);
        AbstractLogicalOperator currentOperator = (AbstractLogicalOperator) currentOpRef.getValue();

        // Recursively eliminates shared references in nested plans.
        if (currentOperator.hasNestedPlans()) {
            // Since a nested plan tree itself can never be shared with another nested plan tree in
            // another operator, the operation called in the if block does not need to replace
            // any variables further for <code>currentOpRef.getValue()</code> nor its ancestor.
            AbstractOperatorWithNestedPlans opWithNestedPlan = (AbstractOperatorWithNestedPlans) currentOperator;
            for (ILogicalPlan plan : opWithNestedPlan.getNestedPlans()) {
                for (Mutable<ILogicalOperator> rootRef : plan.getRoots()) {
                    Set<Mutable<ILogicalOperator>> nestedOpRefSet = new HashSet<>();
                    eliminateSharedOperatorReference(rootRef, nestedOpRefSet);
                }
            }
        }

        int childIndex = 0;
        LinkedHashMap<LogicalVariable, LogicalVariable> varMap = new LinkedHashMap<>();
        for (Mutable<ILogicalOperator> childRef : currentOperator.getInputs()) {
            if (opRefSet.contains(childRef)) {
                // There is a shared operator reference in the query plan.
                // Deep copies the child plan.
                LogicalOperatorDeepCopyWithNewVariablesVisitor visitor = new LogicalOperatorDeepCopyWithNewVariablesVisitor(
                        context, null);
                ILogicalOperator newChild = childRef.getValue().accept(visitor, null);
                LinkedHashMap<LogicalVariable, LogicalVariable> cloneVarMap = visitor
                        .getInputToOutputVariableMapping();

                // Substitute variables according to the deep copy which generates new variables.
                VariableUtilities.substituteVariables(currentOperator, cloneVarMap, null);
                varMap.putAll(cloneVarMap);

                // Sets the new child.
                childRef = new MutableObject<>(newChild);
                currentOperator.getInputs().set(childIndex, childRef);
            }

            // Recursively eliminate shared operator reference for the operator subtree,
            // even if it is a deep copy of some other one.
            LinkedHashMap<LogicalVariable, LogicalVariable> childVarMap = eliminateSharedOperatorReference(
                    childRef, opRefSet);
            // Substitute variables according to the new subtree.
            VariableUtilities.substituteVariables(currentOperator, childVarMap, null);

            // Updates mapping like <$a, $b> in varMap to <$a, $c>, where there is a mapping <$b, $c>
            // in childVarMap.
            for (Map.Entry<LogicalVariable, LogicalVariable> entry : varMap.entrySet()) {
                LogicalVariable newVar = childVarMap.get(entry.getValue());
                if (newVar != null) {
                    entry.setValue(newVar);
                }
            }
            varMap.putAll(childVarMap);
            ++childIndex;
        }

        // Only retain live variables for parent operators to substitute variables.
        Set<LogicalVariable> liveVars = new HashSet<>();
        VariableUtilities.getLiveVariables(currentOperator, liveVars);
        varMap.values().retainAll(liveVars);
        return varMap;
    } catch (AlgebricksException e) {
        throw new AsterixException(e);
    }
}

From source file:com.johan.vertretungsplan.parser.SVPlanParser.java

public Vertretungsplan getVertretungsplan() throws IOException, JSONException {
    new LoginHandler(schule).handleLogin(executor, cookieStore, username, password); //

    JSONArray urls = schule.getData().getJSONArray("urls");
    String encoding = schule.getData().getString("encoding");
    List<Document> docs = new ArrayList<Document>();

    for (int i = 0; i < urls.length(); i++) {
        JSONObject url = urls.getJSONObject(i);
        loadUrl(url.getString("url"), encoding, docs);
    }//from  w  w  w .  j a  v a 2 s  . com

    LinkedHashMap<String, VertretungsplanTag> tage = new LinkedHashMap<String, VertretungsplanTag>();
    for (Document doc : docs) {
        if (doc.select(".svp-tabelle").size() > 0) {
            VertretungsplanTag tag = new VertretungsplanTag();
            String date = "Unbekanntes Datum";
            if (doc.select(".svp-plandatum-heute, .svp-plandatum-morgen").size() > 0)
                date = doc.select(".svp-plandatum-heute, .svp-plandatum-morgen").text();
            else if (doc.title().startsWith("Vertretungsplan fr "))
                date = doc.title().substring("Vertretungsplan fr ".length());
            tag.setDatum(date);
            if (doc.select(".svp-uploaddatum").size() > 0)
                tag.setStand(doc.select(".svp-uploaddatum").text().replace("Aktualisierung: ", ""));

            Elements rows = doc.select(".svp-tabelle tr");
            String lastLesson = "";
            for (Element row : rows) {
                if (row.hasClass("svp-header"))
                    continue;

                Vertretung vertretung = new Vertretung();
                List<String> affectedClasses = new ArrayList<String>();

                for (Element column : row.select("td")) {
                    if (!hasData(column.text())) {
                        continue;
                    }
                    String type = column.className();
                    if (type.startsWith("svp-stunde")) {
                        vertretung.setLesson(column.text());
                        lastLesson = column.text();
                    } else if (type.startsWith("svp-klasse"))
                        affectedClasses = Arrays.asList(column.text().split(", "));
                    else if (type.startsWith("svp-esfehlt"))
                        vertretung.setPreviousTeacher(column.text());
                    else if (type.startsWith("svp-esvertritt"))
                        vertretung.setTeacher(column.text());
                    else if (type.startsWith("svp-fach"))
                        vertretung.setSubject(column.text());
                    else if (type.startsWith("svp-bemerkung")) {
                        vertretung.setDesc(column.text());
                        vertretung.setType(recognizeType(column.text()));
                    } else if (type.startsWith("svp-raum"))
                        vertretung.setRoom(column.text());

                    if (vertretung.getLesson() == null)
                        vertretung.setLesson(lastLesson);
                }

                if (vertretung.getType() == null) {
                    vertretung.setType("Vertretung");
                }

                for (String klasse : affectedClasses) {
                    KlassenVertretungsplan kv = tag.getKlassen().get(klasse);
                    if (kv == null)
                        kv = new KlassenVertretungsplan(klasse);
                    kv.add(vertretung);
                    tag.getKlassen().put(klasse, kv);
                }
            }

            List<String> nachrichten = new ArrayList<String>();
            if (doc.select("h2:contains(Mitteilungen)").size() > 0) {
                Element h2 = doc.select("h2:contains(Mitteilungen)").first();
                Element sibling = h2.nextElementSibling();
                while (sibling != null && sibling.tagName().equals("p")) {
                    for (String nachricht : TextNode.createFromEncoded(sibling.html(), null).getWholeText()
                            .split("<br />\\s*<br />")) {
                        if (hasData(nachricht))
                            nachrichten.add(nachricht);
                    }
                    sibling = sibling.nextElementSibling();
                }
            }
            tag.setNachrichten(nachrichten);

            tage.put(date, tag);
        } else {
            throw new IOException("keine SVPlan-Tabelle gefunden");
        }
    }
    Vertretungsplan v = new Vertretungsplan();
    v.setTage(new ArrayList<VertretungsplanTag>(tage.values()));

    return v;
}

From source file:org.oscarehr.casemgmt.web.CaseManagementEntryAction.java

public void doPrint(HttpServletRequest request, OutputStream os) throws IOException, DocumentException {
    String ids = request.getParameter("notes2print");

    String demono = getDemographicNo(request);
    request.setAttribute("demoName", getDemoName(demono));
    request.setAttribute("demoSex", getDemoSex(demono));
    request.setAttribute("demoAge", getDemoAge(demono));
    request.setAttribute("mrp", getMRP(request));
    String dob = getDemoDOB(demono);
    dob = convertDateFmt(dob, request);/*from   w w w  .  ja  v a  2  s  .  co m*/
    request.setAttribute("demoDOB", dob);
    String providerNo = getProviderNo(request);

    String[] noteIds;
    if (ids.length() > 0)
        noteIds = ids.split(",");
    else
        noteIds = (String[]) Array.newInstance(String.class, 0);

    List<CaseManagementNote> notes = new ArrayList<CaseManagementNote>();
    List<String> remoteNoteUUIDs = new ArrayList<String>();
    String uuid;
    for (int idx = 0; idx < noteIds.length; ++idx) {
        if (noteIds[idx].startsWith("UUID")) {
            uuid = noteIds[idx].substring(4);
            remoteNoteUUIDs.add(uuid);
        } else {
            notes.add(this.caseManagementMgr.getNote(noteIds[idx]));
        }
    }

    LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();
    if (loggedInInfo.currentFacility.isIntegratorEnabled() && remoteNoteUUIDs.size() > 0) {
        DemographicWs demographicWs = CaisiIntegratorManager.getDemographicWs();
        List<CachedDemographicNote> remoteNotes = demographicWs
                .getLinkedCachedDemographicNotes(ConversionUtils.fromIntString(demono));
        for (CachedDemographicNote remoteNote : remoteNotes) {
            for (String remoteUUID : remoteNoteUUIDs) {
                if (remoteUUID.equals(remoteNote.getCachedDemographicNoteCompositePk().getUuid())) {
                    CaseManagementNote fakeNote = getFakedNote(remoteNote);
                    notes.add(fakeNote);
                    break;
                }
            }
        }
    }

    // we're not guaranteed any ordering of notes given to us, so sort by observation date
    oscar.OscarProperties p = oscar.OscarProperties.getInstance();
    String noteSort = p.getProperty("CMESort", "");
    if (noteSort.trim().equalsIgnoreCase("UP")) {
        Collections.sort(notes, CaseManagementNote.noteObservationDateComparator);
        Collections.reverse(notes);
    } else
        Collections.sort(notes, CaseManagementNote.noteObservationDateComparator);

    List<CaseManagementNote> issueNotes;
    List<CaseManagementNote> tmpNotes;
    HashMap<String, List<CaseManagementNote>> cpp = null;
    if (request.getParameter("printCPP").equalsIgnoreCase("true")) {
        cpp = new HashMap<String, List<CaseManagementNote>>();
        String[] issueCodes = { "OMeds", "SocHistory", "MedHistory", "Concerns", "Reminders", "FamHistory",
                "RiskFactors" };
        for (int j = 0; j < issueCodes.length; ++j) {
            List<Issue> issues = caseManagementMgr.getIssueInfoByCode(providerNo, issueCodes[j]);
            String[] issueIds = getIssueIds(issues);// = new String[issues.size()];
            tmpNotes = caseManagementMgr.getNotes(demono, issueIds);
            issueNotes = new ArrayList<CaseManagementNote>();
            for (int k = 0; k < tmpNotes.size(); ++k) {
                if (!tmpNotes.get(k).isLocked()) {
                    List<CaseManagementNoteExt> exts = caseManagementMgr.getExtByNote(tmpNotes.get(k).getId());
                    boolean exclude = false;
                    for (CaseManagementNoteExt ext : exts) {
                        if (ext.getKeyVal().equals("Hide Cpp")) {
                            if (ext.getValue().equals("1")) {
                                exclude = true;
                            }
                        }
                    }
                    if (!exclude) {
                        issueNotes.add(tmpNotes.get(k));
                    }
                }
            }
            cpp.put(issueCodes[j], issueNotes);
        }
    }
    String demoNo = null;
    List<CaseManagementNote> othermeds = null;
    if (request.getParameter("printRx").equalsIgnoreCase("true")) {
        demoNo = demono;
        if (cpp == null) {
            List<Issue> issues = caseManagementMgr.getIssueInfoByCode(providerNo, "OMeds");
            String[] issueIds = getIssueIds(issues);// new String[issues.size()];
            othermeds = caseManagementMgr.getNotes(demono, issueIds);
        } else {
            othermeds = cpp.get("OMeds");
        }
    }

    // Create new file to save form to
    String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    String fileName = path + "EncounterForm-" + UtilDateUtilities.getToday("yyyy-MM-dd.hh.mm.ss") + ".pdf";
    FileOutputStream out = new FileOutputStream(fileName);

    CaseManagementPrintPdf printer = new CaseManagementPrintPdf(request, out);
    printer.printDocHeaderFooter();
    printer.printCPP(cpp);
    printer.printRx(demoNo, othermeds);
    printer.printNotes(notes);

    /* check extensions */
    Enumeration<String> e = request.getParameterNames();
    while (e.hasMoreElements()) {
        String name = e.nextElement();
        if (name.startsWith("extPrint")) {
            if (request.getParameter(name).equals("true")) {
                ExtPrint printBean = (ExtPrint) SpringUtils.getBean(name);
                if (printBean != null) {
                    printBean.printExt(printer, request);
                }
            }
        }
    }
    printer.finish();

    List<Object> pdfDocs = new ArrayList<Object>();
    pdfDocs.add(fileName);

    if (request.getParameter("printLabs") != null
            && request.getParameter("printLabs").equalsIgnoreCase("true")) {
        // get the labs which fall into the date range which are attached to this patient
        CommonLabResultData comLab = new CommonLabResultData();
        ArrayList<LabResultData> labs = comLab.populateLabResultsData("", demono, "", "", "", "U");
        LinkedHashMap<String, LabResultData> accessionMap = new LinkedHashMap<String, LabResultData>();
        for (int i = 0; i < labs.size(); i++) {
            LabResultData result = labs.get(i);
            if (result.isHL7TEXT()) {
                if (result.accessionNumber == null || result.accessionNumber.equals("")) {
                    accessionMap.put("noAccessionNum" + i + result.labType, result);
                } else {
                    if (!accessionMap.containsKey(result.accessionNumber + result.labType))
                        accessionMap.put(result.accessionNumber + result.labType, result);
                }
            }
        }
        for (LabResultData result : accessionMap.values()) {
            Date d = result.getDateObj();
            // TODO:filter out the ones which aren't in our date range if there's a date range????
            String segmentId = result.segmentID;
            MessageHandler handler = Factory.getHandler(segmentId);
            String fileName2 = OscarProperties.getInstance().getProperty("DOCUMENT_DIR") + "//"
                    + handler.getPatientName().replaceAll("\\s", "_") + "_" + handler.getMsgDate()
                    + "_LabReport.pdf";
            OutputStream os2 = new FileOutputStream(fileName2);
            LabPDFCreator pdfCreator = new LabPDFCreator(os2, segmentId,
                    LoggedInInfo.loggedInInfo.get().loggedInProvider.getProviderNo());
            pdfCreator.printPdf();
            pdfDocs.add(fileName2);
        }

    }
    ConcatPDF.concat(pdfDocs, os);
}

From source file:com.griddynamics.jagger.monitoring.reporting.SystemUnderTestPlotsGeneralProvider.java

public Map<String, List<MonitoringReporterData>> createTaskPlots() {
    log.info("BEGIN: Create general task plots");

    Map<String, List<MonitoringReporterData>> taskPlots = new LinkedHashMap<String, List<MonitoringReporterData>>();
    GeneralStatistics generalStatistics = getStatistics();

    Set<String> taskIds = generalStatistics.findTaskIds();
    Set<String> boxIdentifiers = generalStatistics.findBoxIdentifiers();
    Set<String> sutUrls = generalStatistics.findSutUrls();
    for (GroupKey groupName : plotGroups.getPlotGroups().keySet()) {
        log.info("    Create general task plots for group '{}'", groupName);

        if (showPlotsByGlobal) {
            log.info("        Create general global task plots");

            List<MonitoringReporterData> plots = new LinkedList<MonitoringReporterData>();
            XYSeriesCollection chartsCollection = new XYSeriesCollection();
            LinkedHashMap<String, IntervalMarker> markers = new LinkedHashMap<String, IntervalMarker>();
            for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                log.info("            Create general global task plots for parameter '{}'", parameterId);

                MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                if (generalStatistics.hasGlobalStatistics(param)) {
                    XYSeries values = new XYSeries(param.getDescription());
                    long timeShift = 0;
                    int taskNum = 0;
                    for (String taskId : taskIds) {
                        log.info("                Create general global task plots for task '{}'", taskId);

                        long maxTime = 0;
                        for (MonitoringStatistics monitoringStatistics : generalStatistics
                                .findGlobalStatistics(taskId, param)) {
                            long time = monitoringStatistics.getTime();
                            double t = timeShift + time;
                            values.add(t, monitoringStatistics.getAverageValue());

                            if (time > maxTime) {
                                maxTime = time;
                            }/*ww  w .  java 2 s.  c  om*/

                            if (showNumbers) {
                                IntervalMarker marker = markers.get(taskId);
                                if (marker == null) {
                                    marker = new IntervalMarker(t, t);
                                    marker.setLabel(monitoringStatistics.getTaskData().getNumber().toString());
                                    marker.setAlpha((taskNum % 2 == 0) ? 0.2f : 0.4f);

                                    int mod = taskNum % 3;
                                    if (mod == 0) {
                                        marker.setLabelAnchor(RectangleAnchor.CENTER);
                                    } else if (mod == 1) {
                                        marker.setLabelAnchor(RectangleAnchor.TOP);
                                    } else if (mod == 2) {
                                        marker.setLabelAnchor(RectangleAnchor.BOTTOM);
                                    }

                                    marker.setLabelFont(
                                            marker.getLabelFont().deriveFont(10.0f).deriveFont(Font.BOLD));
                                    markers.put(taskId, marker);
                                } else {
                                    if (t < marker.getStartValue()) {
                                        marker.setStartValue(t);
                                    }
                                    if (t > marker.getEndValue()) {
                                        marker.setEndValue(t);
                                    }
                                }
                            }
                        }
                        timeShift += maxTime;
                        taskNum++;
                    }
                    if (values.isEmpty()) {
                        values.add(0, 0);
                    }
                    chartsCollection.addSeries(values);
                }
            }

            log.debug("group name \n{} \nparams {}]\n", groupName,
                    Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

            Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection, markers.values());

            chartsCollection = pair.getSecond();

            String name = groupName.getUpperName();

            if (chartsCollection.getSeriesCount() > 0) {
                JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                        "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 0, 1,
                        ChartHelper.ColorTheme.LIGHT);

                XYPlot plot = (XYPlot) chart.getPlot();
                for (IntervalMarker marker : markers.values()) {
                    plot.addDomainMarker(marker);
                }

                MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                monitoringReporterData.setParameterName(name);
                monitoringReporterData.setTitle(name);
                monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                plots.add(monitoringReporterData);
            }

            if (!plots.isEmpty()) {
                taskPlots.put(name, plots);
            }
        }

        if (showPlotsByBox) {
            log.info("        Create general box task plots");

            for (String boxIdentifier : boxIdentifiers) {
                log.info("            Create general box task plots for box '{}'", boxIdentifier);

                List<MonitoringReporterData> plots = new LinkedList<MonitoringReporterData>();
                XYSeriesCollection chartsCollection = new XYSeriesCollection();
                LinkedHashMap<String, IntervalMarker> markers = new LinkedHashMap<String, IntervalMarker>();
                for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                    log.info("                Create general box task plots for parameter '{}'", parameterId);

                    MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                    if (generalStatistics.hasBoxStatistics(param, boxIdentifier)) {
                        XYSeries values = new XYSeries(param.getDescription());
                        long timeShift = 0;
                        int taskNum = 0;
                        for (String taskId : taskIds) {
                            log.info("                    Create general box task plots for task '{}'", taskId);

                            long maxTime = 0;
                            for (MonitoringStatistics monitoringStatistics : generalStatistics
                                    .findBoxStatistics(taskId, param, boxIdentifier)) {
                                long time = monitoringStatistics.getTime();
                                double t = timeShift + time;
                                values.add(t, monitoringStatistics.getAverageValue());

                                if (time > maxTime) {
                                    maxTime = time;
                                }

                                if (showNumbers) {
                                    IntervalMarker marker = markers.get(taskId);
                                    if (marker == null) {
                                        marker = new IntervalMarker(t, t);
                                        marker.setLabel(
                                                monitoringStatistics.getTaskData().getNumber().toString());
                                        marker.setAlpha((taskNum % 2 == 0) ? 0.2f : 0.4f);

                                        int mod = taskNum % 3;
                                        if (mod == 0) {
                                            marker.setLabelAnchor(RectangleAnchor.CENTER);
                                        } else if (mod == 1) {
                                            marker.setLabelAnchor(RectangleAnchor.TOP);
                                        } else if (mod == 2) {
                                            marker.setLabelAnchor(RectangleAnchor.BOTTOM);
                                        }

                                        marker.setLabelFont(
                                                marker.getLabelFont().deriveFont(10.0f).deriveFont(Font.BOLD));
                                        markers.put(taskId, marker);
                                    } else {
                                        if (t < marker.getStartValue()) {
                                            marker.setStartValue(t);
                                        }
                                        if (t > marker.getEndValue()) {
                                            marker.setEndValue(t);
                                        }
                                    }
                                }
                            }
                            timeShift += maxTime;
                            taskNum++;
                        }
                        if (values.isEmpty()) {
                            values.add(0, 0);
                        }
                        chartsCollection.addSeries(values);
                    }
                }

                log.debug("group name \n{} \nparams {}]\n", groupName,
                        Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

                Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection,
                        markers.values());

                chartsCollection = pair.getSecond();

                String name = groupName.getUpperName() + " on " + boxIdentifier;

                if (chartsCollection.getSeriesCount() > 0) {
                    JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                            "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 0, 1,
                            ChartHelper.ColorTheme.LIGHT);

                    XYPlot plot = (XYPlot) chart.getPlot();
                    for (IntervalMarker marker : markers.values()) {
                        plot.addDomainMarker(marker);
                    }

                    MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                    monitoringReporterData.setParameterName(name);
                    monitoringReporterData.setTitle(name);
                    monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                    plots.add(monitoringReporterData);
                }

                if (!plots.isEmpty()) {
                    taskPlots.put(name, plots);
                }
            }
        }

        if (showPlotsBySuT) {
            log.info("        Create general sut task plots");

            for (String sutUrl : sutUrls) {
                log.info("            Create general sut task plots for sut '{}'", sutUrl);

                List<MonitoringReporterData> plots = new LinkedList<MonitoringReporterData>();
                XYSeriesCollection chartsCollection = new XYSeriesCollection();
                LinkedHashMap<String, IntervalMarker> markers = new LinkedHashMap<String, IntervalMarker>();
                for (MonitoringParameter parameterId : plotGroups.getPlotGroups().get(groupName)) {
                    log.info("                Create general sut task plots for parameter '{}'", parameterId);

                    MonitoringParameterBean param = MonitoringParameterBean.copyOf(parameterId);
                    if (generalStatistics.hasSutStatistics(param, sutUrl)) {
                        XYSeries values = new XYSeries(param.getDescription());
                        long timeShift = 0;
                        int taskNum = 0;
                        for (String taskId : taskIds) {
                            log.info("                    Create general sut task plots for task '{}'", taskId);

                            long maxTime = 0;
                            for (MonitoringStatistics monitoringStatistics : generalStatistics
                                    .findSutStatistics(taskId, param, sutUrl)) {
                                long time = monitoringStatistics.getTime();
                                double t = timeShift + time;
                                values.add(t, monitoringStatistics.getAverageValue());

                                if (time > maxTime) {
                                    maxTime = time;
                                }

                                if (showNumbers) {
                                    IntervalMarker marker = markers.get(taskId);
                                    if (marker == null) {
                                        marker = new IntervalMarker(t, t);
                                        marker.setLabel(
                                                monitoringStatistics.getTaskData().getNumber().toString());
                                        marker.setAlpha((taskNum % 2 == 0) ? 0.2f : 0.4f);

                                        int mod = taskNum % 3;
                                        if (mod == 0) {
                                            marker.setLabelAnchor(RectangleAnchor.CENTER);
                                        } else if (mod == 1) {
                                            marker.setLabelAnchor(RectangleAnchor.TOP);
                                        } else if (mod == 2) {
                                            marker.setLabelAnchor(RectangleAnchor.BOTTOM);
                                        }

                                        marker.setLabelFont(
                                                marker.getLabelFont().deriveFont(10.0f).deriveFont(Font.BOLD));
                                        markers.put(taskId, marker);
                                    } else {
                                        if (t < marker.getStartValue()) {
                                            marker.setStartValue(t);
                                        }
                                        if (t > marker.getEndValue()) {
                                            marker.setEndValue(t);
                                        }
                                    }
                                }
                            }
                            timeShift += maxTime;
                            taskNum++;
                        }
                        if (values.isEmpty()) {
                            values.add(0, 0);
                        }
                        chartsCollection.addSeries(values);
                    }
                }

                log.debug("group name \n{} \nparams {}]\n", groupName,
                        Lists.newArrayList(plotGroups.getPlotGroups().get(groupName)));

                Pair<String, XYSeriesCollection> pair = ChartHelper.adjustTime(chartsCollection,
                        markers.values());

                chartsCollection = pair.getSecond();

                String name = groupName.getUpperName() + " on " + sutUrl;

                if (chartsCollection.getSeriesCount() > 0) {
                    JFreeChart chart = ChartHelper.createXYChart(null, chartsCollection,
                            "Time (" + pair.getFirst() + ")", groupName.getLeftName(), 0, 1,
                            ChartHelper.ColorTheme.LIGHT);

                    XYPlot plot = (XYPlot) chart.getPlot();
                    for (IntervalMarker marker : markers.values()) {
                        plot.addDomainMarker(marker);
                    }

                    MonitoringReporterData monitoringReporterData = new MonitoringReporterData();
                    monitoringReporterData.setParameterName(name);
                    monitoringReporterData.setTitle(name);
                    monitoringReporterData.setPlot(new JCommonDrawableRenderer(chart));
                    plots.add(monitoringReporterData);
                }

                if (!plots.isEmpty()) {
                    taskPlots.put(name, plots);
                }
            }
        }
    }

    clearStatistics();

    log.info("END: Create general task plots");

    return taskPlots;
}

From source file:com.perceptive.epm.perkolcentral.bl.EmployeeBL.java

@TriggersRemove(cacheName = { "EmployeeCache", "GroupCache",
        "EmployeeKeyedByGroupCache" }, when = When.AFTER_METHOD_INVOCATION, removeAll = true, keyGenerator = @KeyGenerator(name = "HashCodeCacheKeyGenerator", properties = @Property(name = "includeMethod", value = "false")))
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.SERIALIZABLE, rollbackFor = ExceptionWrapper.class)
public void updateAllEmployee(List<EmployeeBO> employeeListFromLDAP) throws ExceptionWrapper {
    try {/*  ww  w . j a v  a2  s.co m*/
        String messageTemplateAdded = "<html>\n" + "<head>\n" + "</head>\n" + "\n"
                + "<body style=\"font:Georgia; font-size:12px;\">\n" + "<p>Dear All,</p>\n" + "<blockquote>\n"
                + "  <p>A new user is added to the system.</p>\n" + "</blockquote>\n" + "<ul>\n"
                + "  <li><strong><em>User Name</em></strong>: <strong>%s</strong></li>\n"
                + "  <li><em><strong>User Short Id</strong></em>: <strong>%s</strong></li>\n"
                + "  <li><em><strong>Employee Id</strong></em>: <strong>%s</strong></li>\n"
                + "  <li><strong><em>User Email-Id</em></strong>:<strong> %s</strong></li>\n"
                + "  <li><em><strong>Mobile Number</strong></em>:<strong> %s</strong></li>\n"
                + "  <li><em><strong>Job Title</strong></em> : <strong>%s</strong></li>\n" + "</ul>\n"
                + "<p>Please take necessary actions.</p>\n" + "<p>Thanks,</p>\n" + "<blockquote>\n"
                + "  <p>Perceptive Kolkata Central</p>\n" + "</blockquote>\n" + "</body>\n" + "</html>";

        String messageTemplateDeleted = "<html>\n" + "<head>\n" + "</head>\n" + "\n"
                + "<body style=\"font:Georgia; font-size:12px;\">\n" + "<p>Dear All,</p>\n" + "<blockquote>\n"
                + "  <p>An  user is removed from the system.</p>\n" + "</blockquote>\n" + "<ul>\n"
                + "  <li><strong><em>User Name</em></strong>: <strong>%s</strong></li>\n"
                + "  <li><em><strong>User Short Id</strong></em>: <strong>%s</strong></li>\n"
                + "  <li><em><strong>Employee Id</strong></em>: <strong>%s</strong></li>\n"
                + "  <li><strong><em>User Email-Id</em></strong>:<strong> %s</strong></li>\n"
                + "  <li><em><strong>Mobile Number</strong></em>:<strong> %s</strong></li>\n"
                + "  <li><em><strong>Job Title</strong></em> : <strong>%s</strong></li>\n" + "</ul>\n"
                + "<p>Please take necessary actions.</p>\n" + "<p>Thanks,</p>\n" + "<blockquote>\n"
                + "  <p>Perceptive Kolkata Central</p>\n" + "</blockquote>\n" + "</body>\n" + "</html>";

        LinkedHashMap<Long, EmployeeBO> employeeLinkedHashMap = employeeDataAccessor.getAllEmployees();
        for (EmployeeBO employeeBO : employeeListFromLDAP) {
            if (!employeeLinkedHashMap.containsKey(Long.valueOf(employeeBO.getEmployeeId()))) {
                //Add a new employee
                Employee employee = new Employee();
                employee.setEmployeeId(Long.parseLong(employeeBO.getEmployeeId()));
                employee.setEmail(employeeBO.getEmail());
                employee.setEmployeeName(employeeBO.getEmployeeName());
                employee.setEmployeeUid(employeeBO.getEmployeeUid());
                employee.setJobTitle(employeeBO.getJobTitle());
                employee.setMobileNumber(employeeBO.getMobileNumber());
                employee.setManager(employeeBO.getManager());
                employee.setManagerEmail(employeeBO.getManagerEmail());
                employee.setExtensionNum(employeeBO.getExtensionNum());
                employee.setWorkspace(employeeBO.getWorkspace());
                employee.setIsActive(true);
                employeeDataAccessor.addEmployee(employee);
                LoggingHelpUtil.printDebug(String.format("Adding user ----> %s with details %s %s",
                        employeeBO.getEmployeeName(), System.getProperty("line.separator"),
                        ReflectionToStringBuilder.toString(employeeBO)));
                //Send the mail
                HtmlEmail emailToSend = new HtmlEmail();
                emailToSend.setHostName(email.getHostName());
                String messageToSend = String.format(messageTemplateAdded, employeeBO.getEmployeeName(),
                        employeeBO.getEmployeeUid(), employeeBO.getEmployeeId().toString(),
                        employeeBO.getEmail(), employeeBO.getMobileNumber(), employeeBO.getJobTitle());

                emailToSend.setHtmlMsg(messageToSend);
                //emailToSend.setTextMsg(StringEscapeUtils.escapeHtml(messageToSend));
                emailToSend.getToAddresses().clear();
                //Send mail to scrum masters and Development Managers Group Id 15
                Collection<EmployeeBO> allEmployeesNeedToGetMail = CollectionUtils.union(
                        getAllEmployeesKeyedByGroupId().get(Integer.valueOf("14")),
                        getAllEmployeesKeyedByGroupId().get(Integer.valueOf("15")));
                for (EmployeeBO item : allEmployeesNeedToGetMail) {
                    emailToSend.addTo(item.getEmail(), item.getEmployeeName());
                }
                emailToSend.addTo(employeeBO.getManagerEmail(), employeeBO.getManager());//Send the mail to manager
                //emailToSend.setFrom("PerceptiveKolkataCentral@perceptivesoftware.com", "Perceptive Kolkata Central");
                emailToSend.setFrom("EnterpriseSoftwareKolkata@lexmark.com", "Enterprise Software Kolkata");
                emailToSend.setSubject(String.format("New employee added : %s", employeeBO.getEmployeeName()));
                emailToSend.send();
                //==========================Mail send ends here===========================================================================================================
                //sendMailToPerceptiveOpsTeam(employeeBO);//Send mail to operations team in Shawnee
            } else {
                //Update a new employee
                employeeDataAccessor.updateEmployee(employeeBO);
                LoggingHelpUtil.printDebug(String.format("Updating user ----> %s with details %s %s",
                        employeeBO.getEmployeeName(), System.getProperty("line.separator"),
                        ReflectionToStringBuilder.toString(employeeBO)));
            }

            //========================================================================================================================================
        }
        //Delete employees if any
        for (Object obj : employeeLinkedHashMap.values()) {
            final EmployeeBO emp = (EmployeeBO) obj;
            if (!CollectionUtils.exists(employeeListFromLDAP, new Predicate() {
                @Override
                public boolean evaluate(Object o) {
                    return emp.getEmployeeId().trim().equalsIgnoreCase(((EmployeeBO) o).getEmployeeId().trim()); //To change body of implemented methods use File | Settings | File Templates.
                }
            })) {
                emp.setActive(false); //Soft delete the Employee
                employeeDataAccessor.updateEmployee(emp);//Rest deletion will be taken care by the Trigger AFTER_EMPLOYEE_UPDATE
                LoggingHelpUtil.printDebug(
                        String.format("Deleting user ----> %s with details %s %s", emp.getEmployeeName(),
                                System.getProperty("line.separator"), ReflectionToStringBuilder.toString(emp)));
                //Send the mail
                HtmlEmail emailToSend = new HtmlEmail();
                emailToSend.setHostName(email.getHostName());

                String messageToSend = String.format(messageTemplateDeleted, emp.getEmployeeName(),
                        emp.getEmployeeUid(), emp.getEmployeeId().toString(), emp.getEmail(),
                        emp.getMobileNumber(), emp.getJobTitle());
                emailToSend.setHtmlMsg(messageToSend);
                //emailToSend.setTextMsg(StringEscapeUtils.escapeHtml(messageToSend));
                emailToSend.getToAddresses().clear();
                //Send mail to scrum masters ==Group ID 14 and Development Managers Group Id 15
                Collection<EmployeeBO> allEmployeesNeedToGetMail = CollectionUtils.union(
                        getAllEmployeesKeyedByGroupId().get(Integer.valueOf("14")),
                        getAllEmployeesKeyedByGroupId().get(Integer.valueOf("15")));
                for (EmployeeBO item : allEmployeesNeedToGetMail) {
                    emailToSend.addTo(item.getEmail(), item.getEmployeeName());
                }
                //emailToSend.setFrom("PerceptiveKolkataCentral@perceptivesoftware.com", "Perceptive Kolkata Central");
                emailToSend.setFrom("EnterpriseSoftwareKolkata@lexmark.com", "Enterprise Software Kolkata");
                emailToSend.setSubject(String.format("Employee removed : %s", emp.getEmployeeName()));
                emailToSend.send();
            }
        }

        luceneUtil.indexUserInfo(getAllEmployees().values());

    } catch (Exception ex) {
        throw new ExceptionWrapper(ex);
    }
}

From source file:org.jamwiki.db.AnsiQueryHandler.java

/**
 *
 *//*w  w  w .  j av a2 s.c  om*/
public List<RoleMap> getRoleMapGroups() throws SQLException {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        conn = DatabaseConnection.getConnection();
        stmt = conn.prepareStatement(STATEMENT_SELECT_GROUPS_AUTHORITIES);
        rs = stmt.executeQuery();
        LinkedHashMap<Integer, RoleMap> roleMaps = new LinkedHashMap<Integer, RoleMap>();
        while (rs.next()) {
            Integer groupId = rs.getInt("group_id");
            RoleMap roleMap = new RoleMap();
            if (roleMaps.containsKey(groupId)) {
                roleMap = roleMaps.get(groupId);
            } else {
                roleMap.setGroupId(groupId);
                roleMap.setGroupName(rs.getString("group_name"));
            }
            roleMap.addRole(rs.getString("authority"));
            roleMaps.put(groupId, roleMap);
        }
        return new ArrayList<RoleMap>(roleMaps.values());
    } finally {
        DatabaseConnection.closeConnection(conn, stmt, rs);
    }
}