Example usage for java.util List removeAll

List of usage examples for java.util List removeAll

Introduction

In this page you can find the example usage for java.util List removeAll.

Prototype

boolean removeAll(Collection<?> c);

Source Link

Document

Removes from this list all of its elements that are contained in the specified collection (optional operation).

Usage

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.UserAuthorityServiceImpl.java

@Transactional(propagation = Propagation.REQUIRED)
public List getUsersNotInRole(ExecutionContext context, String roleName) {
    List allUsers = getUsers(context, null);
    List usersInRole = getUsersInRole(context, roleName);
    allUsers.removeAll(usersInRole);

    return allUsers;
}

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.UserAuthorityServiceImpl.java

@Transactional(propagation = Propagation.REQUIRED)
public List getAvailableRoles(ExecutionContext context, String userName) {
    List allRoles = getRoles(context, null);
    List assignedRoles = getAssignedRoles(null, userName);
    allRoles.removeAll(assignedRoles);
    return allRoles;
}

From source file:gov.nih.nci.cabig.caaers.rules.business.service.EvaluationServiceImpl.java

/**
 * This method invokes the {@link AdverseEventEvaluationService} to obtain the report definitions suggested. 
 * Then process that information, to get the adverse event result {@link EvaluationResultDTO}
 * /*from ww  w.j a  va 2  s .c om*/
 * Overview on extra processing
 *   0. Ignore all the 'soft deleted' reports suggested by rules engine. 
 *   1. If child report or a report of the same group is active , parent report suggested by rules is ignored.
 *   2. All manually selected active reports are suggested by caAERS
 *   3. If there is a manual selection, ignore the others suggested by rules
 *   4. If there is an AE modified, which is part of submitted report, force amend it. 
 *   5. If any, Withdraw all active reports (non manually selected), that are not suggested.
 *   
 * @param aeReport - The {@link ExpeditedAdverseEventReport}
 */
public void findRequiredReportDefinitions(ExpeditedAdverseEventReport aeReport, List<AdverseEvent> aeList,
        Study study, EvaluationResultDTO evaluationResult) {
    Map<AdverseEvent, List<ReportDefinition>> adverseEventRecommendedReportsMap = new HashMap<AdverseEvent, List<ReportDefinition>>();

    List<AdverseEvent> deletedAeList = new ArrayList<AdverseEvent>();
    List<AdverseEvent> newAeList = new ArrayList<AdverseEvent>();
    List<AdverseEvent> modifiedAeList = new ArrayList<AdverseEvent>();
    List<AdverseEvent> evaluatableAeList = new ArrayList<AdverseEvent>();
    for (AdverseEvent ae : aeList) {
        if (ae.isRetired()) {
            deletedAeList.add(ae);
        } else if (ae.getReport() == null) {
            newAeList.add(ae);
        } else {
            modifiedAeList.add(ae);
        }
    }

    evaluatableAeList.addAll(modifiedAeList);
    evaluatableAeList.addAll(newAeList);

    ExpeditedAdverseEventReport expeditedData = aeReport.getId() == null ? null : aeReport;
    //to hold the report defnitions while cleaning up. 
    Map<String, ReportDefinition> loadedReportDefinitionsMap = new HashMap<String, ReportDefinition>();

    Map<AdverseEvent, List<AdverseEventEvaluationResult>> adverseEventEvaluationResultMap;
    Map<AdverseEvent, List<String>> map;

    boolean alertNeeded = false;
    Integer aeReportId = expeditedData == null ? new Integer(0) : expeditedData.getId();
    try {
        //evaluate the SAE reporting rules
        adverseEventEvaluationResultMap = adverseEventEvaluationService.evaluateSAEReportSchedule(aeReport,
                evaluatableAeList, study);
        evaluationResult.getRulesEngineRawResultMap().put(aeReportId, adverseEventEvaluationResultMap);
        map = new HashMap<AdverseEvent, List<String>>();

        // clear the recommended reports map
        adverseEventRecommendedReportsMap.clear();

        //clean up - by eliminating the deleted report definitions.
        for (Map.Entry<AdverseEvent, List<AdverseEventEvaluationResult>> entry : adverseEventEvaluationResultMap
                .entrySet()) {
            Set<String> rdNameSet = new HashSet<String>();
            AdverseEvent adverseEvent = entry.getKey();
            Set<ReportDefinition> recommendedAeReports = new HashSet<ReportDefinition>();
            for (AdverseEventEvaluationResult aeEvalResult : entry.getValue()) {
                for (String response : aeEvalResult.getRuleEvaluationResult().getResponses()) {
                    if (!StringUtils.isBlank(response)) {
                        ReportDefinition rd = reportDefinitionDao.getByName(response);
                        if (rd != null) {
                            recommendedAeReports.add(rd);
                        }
                    }
                }
            }
            adverseEventRecommendedReportsMap.put(adverseEvent,
                    new ArrayList<ReportDefinition>(recommendedAeReports));

            List<String> validReportDefNames = new ArrayList<String>();
            map.put(adverseEvent, validReportDefNames);
            evaluationResult.addProcessingStep(aeReportId, "RulesEngine: Evaluation for adverse event ("
                    + AdverseEvent.toReadableString(adverseEvent) + ") :", null);
            for (AdverseEventEvaluationResult adverseEventEvaluationResult : entry.getValue()) {
                evaluationResult.addProcessingStep(aeReportId, " RuleSet:",
                        adverseEventEvaluationResult.getRuleMetadata());
                evaluationResult.addProcessingStep(aeReportId, " Raw message :",
                        adverseEventEvaluationResult.getMessage());
                if (adverseEventEvaluationResult.getRuleEvaluationResult() != null) {
                    evaluationResult.addProcessingStep(aeReportId, " Bind URL :",
                            adverseEventEvaluationResult.getRuleEvaluationResult().getBindURI());
                    evaluationResult.addProcessingStep(aeReportId, " Matched rules :",
                            adverseEventEvaluationResult.getRuleEvaluationResult().getMatchedRules()
                                    .toString());
                    for (String note : adverseEventEvaluationResult.getNotes()) {
                        evaluationResult.addProcessingStep(aeReportId, "  Notes: ", note);
                    }
                    evaluationResult.addProcessingStep(aeReportId, " Matched rules :",
                            adverseEventEvaluationResult.getRuleEvaluationResult().getMatchedRules()
                                    .toString());

                } else {
                    evaluationResult.addProcessingStep(aeReportId, " Bind URL :", null);
                    evaluationResult.addProcessingStep(aeReportId, " Matched rules :", null);
                }

                if (adverseEventEvaluationResult.isCannotDetermine()
                        || adverseEventEvaluationResult.isNoRulesFound())
                    continue;

                evaluationResult.addProcessingStep(aeReportId, " Raw suggestions :",
                        adverseEventEvaluationResult.getRuleEvaluationResult().getResponses().toString());

                rdNameSet.addAll(adverseEventEvaluationResult.getRuleEvaluationResult().getResponses());
            }

            //CAAERS-5702
            if (rdNameSet.contains("IGNORE")) {
                rdNameSet.clear();
                evaluationResult.addProcessingStep(aeReportId,
                        "caAERS : Protocol specific exception, so removing all recommendations", "");
            }

            for (String reportDefName : rdNameSet) {
                ReportDefinition rd = loadedReportDefinitionsMap.get(reportDefName);
                if (rd == null) {
                    rd = reportDefinitionDao.getByName(reportDefName);
                    if (rd == null) {
                        evaluationResult.addProcessingStep(aeReportId, "report definition missing in database ",
                                reportDefName);
                        log.warn("Report definition (" + reportDefName
                                + "), is referred in rules but is not found");
                        continue; //we cannot find the report referred by the rule
                    }
                    if (rd.getEnabled()) {
                        loadedReportDefinitionsMap.put(reportDefName, rd);
                    } else {
                        log.debug("Ignoring Report definition [" + reportDefName + "] as it is disabled");
                    }
                }

                if (rd.getEnabled()) {
                    validReportDefNames.add(reportDefName);
                }

            }
            evaluationResult.addProcessingStep(aeReportId, "caAERS : Plausible suggestions :",
                    validReportDefNames.toString());
            evaluationResult.addProcessingStep(aeReportId, " ", null);

        }

        for (Map.Entry<AdverseEvent, List<ReportDefinition>> entry : adverseEventRecommendedReportsMap
                .entrySet()) {
            List<ReportDefinition> filteredRdList = reportDefinitionFilter.filter(entry.getValue());
            entry.setValue(filteredRdList);
        }

        //save this for reference.
        evaluationResult.addRulesEngineResult(aeReportId, map);

        //now load report definitions
        List<ReportDefinition> defList = new ArrayList<ReportDefinition>();
        defList.addAll(loadedReportDefinitionsMap.values());

        List<Report> completedReports = expeditedData == null ? new ArrayList<Report>()
                : expeditedData.listReportsHavingStatus(ReportStatus.COMPLETED);

        //Remove all NOTIFICATIONS from completed reports. As notifications must be completed by a subsequent full report.
        List<Report> notificationsToRemove = new ArrayList<Report>();
        for (Report report : completedReports) {
            List<ReportDefinition> rdList = ReportDefinition.findByName(defList, report.getName());
            if (!rdList.isEmpty() && rdList.get(0).getReportType() == ReportType.NOTIFICATION) {
                notificationsToRemove.add(report);
            }
        }
        completedReports.removeAll(notificationsToRemove);

        if (!completedReports.isEmpty()) {

            for (AdverseEvent adverseEvent : evaluatableAeList) {

                if (adverseEvent.getReport() == null)
                    continue; //unreported AE -  continue

                List<String> nameList = map.get(adverseEvent);

                if (adverseEvent.isModified()) {
                    //throw away notifications if AE is already reported.
                    for (Report report : completedReports) {
                        if (report.isReported(adverseEvent)) {
                            List<ReportDefinition> rdList = ReportDefinition.findByName(defList,
                                    nameList.toArray(new String[0]));
                            List<ReportDefinition> sameOrgGroupList = ReportDefinition
                                    .findBySameOrganizationAndGroup(rdList, report.getReportDefinition());
                            if (sameOrgGroupList.size() > 1) {
                                List<ReportDefinition> rdNotificationList = ReportDefinition
                                        .findByReportType(sameOrgGroupList, ReportType.NOTIFICATION);
                                for (ReportDefinition rd : rdNotificationList) {
                                    // we must remove these from suggestions.
                                    nameList.remove(rd.getName());
                                    boolean removed = defList.remove(rd);
                                    evaluationResult.removeReportDefinitionName(aeReportId, adverseEvent,
                                            rd.getName());
                                    evaluationResult.addProcessingStep(aeReportId,
                                            "caAERS : Adverse event ("
                                                    + AdverseEvent.toReadableString(adverseEvent)
                                                    + ") is already reported in :",
                                            "" + report.getId());
                                    evaluationResult.addProcessingStep(aeReportId,
                                            " Notifications are not needed again, removing:", rd.getName());
                                    evaluationResult.addProcessingStep(aeReportId, " removed ? :",
                                            String.valueOf(removed));
                                }

                            }
                        }
                    }
                } else {
                    //throw away rules suggestion - if AE is not modified and is part of a submitted report OR if AE is new

                    for (Report report : completedReports) {
                        if (report.isReported(adverseEvent)) {
                            nameList.remove(report.getName());
                            List<ReportDefinition> rdList = ReportDefinition.findByName(defList,
                                    new String[] { report.getName() });
                            if (!rdList.isEmpty())
                                defList.remove(rdList.get(0));
                            evaluationResult.removeReportDefinitionName(aeReportId, adverseEvent,
                                    report.getName());
                            evaluationResult.addProcessingStep(aeReportId, "caAERS : Adverse event ("
                                    + AdverseEvent.toReadableString(adverseEvent) + "):", null);
                            evaluationResult.addProcessingStep(aeReportId,
                                    " Unmodified and belongs to completed report :", null);
                            evaluationResult.addProcessingStep(aeReportId, " Removing suggestion :",
                                    report.getName());

                        }
                    }

                }

            }
        }

        //Update AE reporting flag (or sae flag)
        for (AdverseEvent ae : map.keySet()) {
            List<String> nameList = map.get(ae);
            ae.setRequiresReporting(!nameList.isEmpty());
            evaluationResult.addProcessingStep(aeReportId,
                    "caAERS: Adverse event (" + AdverseEvent.toReadableString(ae) + ") may need reporting ? : ",
                    String.valueOf(ae.getRequiresReporting()));
        }

        //logging
        if (log.isDebugEnabled()) {
            log.debug("Rules Engine Result for : " + aeReportId + ", " + String.valueOf(map));
        }

        //  - If child report is active, select that instead of parent. 
        // - If there is a manual selection, ignore rules engine suggestions from the same group
        // - If the manual selection is always a preferred one (ie. by default add active manual selected reports). 
        // - If there is an ae modified, which is part of completed report, force amending it.
        List<Report> activeReports = null;
        if (expeditedData != null) {
            activeReports = expeditedData.getActiveReports();
            List<Report> manuallySelectedReports = expeditedData.getManuallySelectedReports();

            //a temporary list
            List<ReportDefinition> tmplist = new ArrayList<ReportDefinition>(defList);

            //keep active child report instead of parent.
            for (Report activeReport : activeReports) {
                ReportDefinition rdParent = activeReport.getReportDefinition().getParent();
                ReportDefinition rdFound = findReportDefinition(tmplist, rdParent);

                if (rdFound != null) {
                    //remove parent and keep child
                    defList.remove(rdFound);
                    defList.add(activeReport.getReportDefinition());
                    evaluationResult.replaceReportDefinitionName(aeReportId, rdFound.getName(),
                            activeReport.getName());
                    evaluationResult.addProcessingStep(aeReportId,
                            "caAERS: Active child report (" + activeReport.getName() + ") present", null);
                    evaluationResult.addProcessingStep(aeReportId, " Removing suggestion", rdFound.getName());
                }
            }

            //throw away all suggestions of rules engine, (if they belong to the same group as that of manually selected)
            for (Report manualReport : manuallySelectedReports) {
                ReportDefinition rdManual = manualReport.getReportDefinition();

                for (ReportDefinition rdSuggested : tmplist) {
                    if (rdSuggested.isOfSameReportTypeAndOrganization(rdManual) && manualReport.isActive()) {
                        //remove it from rules engine suggestions
                        defList.remove(rdSuggested);
                        evaluationResult.replaceReportDefinitionName(aeReportId, rdSuggested.getName(),
                                rdManual.getName());
                        evaluationResult.addProcessingStep(aeReportId,
                                "caAERS: Manually selected report (" + rdManual.getName() + ") present", null);
                        evaluationResult.addProcessingStep(aeReportId, " Removing suggestion",
                                rdSuggested.getName());
                    }
                }

                //now add the manually selected report.
                defList.add(rdManual);
                evaluationResult.addReportDefinitionName(aeReportId, rdManual.getName());
                evaluationResult.addProcessingStep(aeReportId, " Adding to suggestion ", rdManual.getName());

            }

            //any ae modified/got completed reports ? add those report definitions.
            if (defList.isEmpty() && !modifiedAeList.isEmpty()) {
                //Any completed report, suggest amending it to proceed (but no alert).
                for (Report report : completedReports) {

                    ReportDefinition rdCompleted = report.getReportDefinition();

                    if (!rdCompleted.getAmendable())
                        continue;

                    defList.add(rdCompleted);
                    for (AdverseEvent ae : modifiedAeList) {
                        evaluationResult.addReportDefinitionName(aeReportId, ae, rdCompleted.getName());
                        evaluationResult.addProcessingStep(aeReportId, "caAERS: Submitted adverse event ("
                                + AdverseEvent.toReadableString(ae) + ") is modified : ", null);
                        evaluationResult.addProcessingStep(aeReportId, " Adding to suggestion ",
                                rdCompleted.getName());

                    }

                }
            }

            //CAAERS-7067 - the deletions must suggest an Amend (ONLY if the AE was reported on last submitted report)
            if (!deletedAeList.isEmpty()) {
                // find latest submission from each group and org
                List<Report> lastSubmittedReports = new ArrayList<Report>();
                Set<Integer> rdIdSet = new HashSet<Integer>(); //using Set for reports may complicate stuff with equals on hibernate proxy
                for (Report completedReport : completedReports) {
                    Report latestReport = aeReport
                            .findLastSubmittedReport(completedReport.getReportDefinition());
                    if (rdIdSet.add(latestReport.getReportDefinition().getId())) {
                        lastSubmittedReports.add(latestReport);
                    }
                }

                //for each such report, if the AE deleted is submitted on that, then suggest ammend.
                for (Report submittedReport : lastSubmittedReports) {
                    ReportDefinition rdCompleted = submittedReport.getReportDefinition();
                    if (rdCompleted.getReportType() == ReportType.NOTIFICATION)
                        continue; //CAAERS-7041
                    if (!rdCompleted.getAmendable())
                        continue;

                    for (AdverseEvent ae : deletedAeList) {
                        boolean reported = submittedReport.isReported(ae);
                        if (reported) {
                            defList.add(rdCompleted);
                            evaluationResult.addReportDefinitionName(aeReportId, ae, rdCompleted.getName());
                            evaluationResult.addProcessingStep(aeReportId, "caAERS: Submitted adverse event ("
                                    + AdverseEvent.toReadableString(ae) + ") is deleted : ", null);
                            evaluationResult.addProcessingStep(aeReportId, " Adding to suggestion ",
                                    rdCompleted.getName());
                        }
                    }
                }
            }

        }

        //logging 
        if (log.isDebugEnabled()) {
            log.debug("Report Definitions before filtering for aeReportId: " + aeReportId + ", "
                    + String.valueOf(defList));
        }

        //filter the report definitions
        List<ReportDefinition> reportDefinitions = reportDefinitionFilter.filter(defList);

        if (reportDefinitions != null) {
            List<String> filteredReportDefnitionNames = new ArrayList<String>();
            for (ReportDefinition rd : reportDefinitions) {
                filteredReportDefnitionNames.add(rd.getName());
            }
            evaluationResult.addProcessingStep(aeReportId, " ", null);
            evaluationResult.addProcessingStep(aeReportId, "caAERS: Final suggestion after filtering :",
                    filteredReportDefnitionNames.toString());
        }

        //modify the alert necessary flag, based on eventual set of report definitions
        if (expeditedData == null) {
            alertNeeded = !reportDefinitions.isEmpty();
        } else {
            for (ReportDefinition reportDefinition : reportDefinitions) {
                alertNeeded |= expeditedData.findReportsToEdit(reportDefinition).isEmpty();
            }
        }
        evaluationResult.getAeReportAlertMap().put(aeReportId, alertNeeded);
        evaluationResult.addProcessingStep(aeReportId, "caAERS: Alert is needed ? ",
                String.valueOf(alertNeeded));

        //logging 
        if (log.isDebugEnabled()) {
            log.debug("Report Definitions after filtering for aeReportId: " + aeReportId + ", "
                    + String.valueOf(reportDefinitions));
        }

        //now go through each report definition and set amend/create edit/withdraw/create maps properly
        Set<ReportDefinitionWrapper> rdCreateSet = new HashSet<ReportDefinitionWrapper>();
        Set<ReportDefinitionWrapper> rdEditSet = new HashSet<ReportDefinitionWrapper>();
        Set<ReportDefinitionWrapper> rdWithdrawSet = new HashSet<ReportDefinitionWrapper>();
        Set<ReportDefinitionWrapper> rdAmmendSet = new HashSet<ReportDefinitionWrapper>();

        ReportDefinitionWrapper wrapper;
        for (ReportDefinition rd : reportDefinitions) {

            if (expeditedData == null) {
                //all report definitions, should go in the createMap.
                wrapper = new ReportDefinitionWrapper(rd, null, ActionType.CREATE);
                wrapper.setStatus("Not started");
                rdCreateSet.add(wrapper);
            } else {

                //find reports getting amended
                List<Report> reportsAmmended = expeditedData.findReportsToAmmend(rd);
                for (Report report : reportsAmmended) {
                    wrapper = new ReportDefinitionWrapper(report.getReportDefinition(), rd, ActionType.AMEND);
                    wrapper.setStatus(report.getLastVersion().getStatusAsString());
                    wrapper.setSubmittedOn(report.getSubmittedOn());
                    rdAmmendSet.add(wrapper);
                }

                //find reports getting withdrawn
                List<Report> reportsWithdrawn = expeditedData.findReportsToWithdraw(rd);
                for (Report report : reportsWithdrawn) {
                    wrapper = new ReportDefinitionWrapper(report.getReportDefinition(), rd,
                            ActionType.WITHDRAW);
                    wrapper.setStatus("In process");
                    wrapper.setDueOn(report.getDueOn());
                    rdWithdrawSet.add(wrapper);
                }

                //find the reports getting edited
                List<Report> reportsEdited = expeditedData.findReportsToEdit(rd);
                for (Report report : reportsEdited) {
                    wrapper = new ReportDefinitionWrapper(report.getReportDefinition(), rd, ActionType.EDIT);
                    wrapper.setStatus("In process");
                    wrapper.setDueOn(report.getDueOn());
                    rdEditSet.add(wrapper);
                }

                //Nothing getting edited,  add in this report def in create list
                if (reportsEdited.isEmpty() && reportsAmmended.isEmpty() && reportsWithdrawn.isEmpty()) {
                    wrapper = new ReportDefinitionWrapper(rd, null, ActionType.CREATE);
                    wrapper.setStatus("Not started");
                    rdCreateSet.add(wrapper);
                }

            } //if expeditedData  

        } //for rd

        //Check if there is a need to withdraw any active report. 
        if (expeditedData != null && activeReports != null) {
            for (Report report : activeReports) {
                ReportDefinition rdActive = report.getReportDefinition();
                if (report.isManuallySelected())
                    continue;
                boolean toBeWithdrawn = true;
                for (ReportDefinitionWrapper editWrapper : rdEditSet) {
                    if (editWrapper.getDef().equals(rdActive)) {
                        toBeWithdrawn = false;
                        break;
                    }
                }

                if (toBeWithdrawn) {
                    for (ReportDefinitionWrapper withdrawWrapper : rdWithdrawSet) {
                        if (withdrawWrapper.getDef().equals(rdActive)) {
                            toBeWithdrawn = false;
                            break;
                        }
                    }
                }

                if (toBeWithdrawn) {
                    wrapper = new ReportDefinitionWrapper(rdActive, null, ActionType.WITHDRAW);
                    wrapper.setDueOn(report.getDueOn());
                    wrapper.setStatus("In process");
                    rdWithdrawSet.add(wrapper);
                }
            }
        }

        //add everything to the result.
        evaluationResult.getCreateMap().put(aeReportId, rdCreateSet);
        evaluationResult.getAmendmentMap().put(aeReportId, rdAmmendSet);
        evaluationResult.getEditMap().put(aeReportId, rdEditSet);
        evaluationResult.getWithdrawalMap().put(aeReportId, rdWithdrawSet);

        if (!rdCreateSet.isEmpty()) {
            evaluationResult.addProcessingStep(aeReportId, "caAERS: Create options :", null);
            for (ReportDefinitionWrapper rdWrapper : rdCreateSet) {
                evaluationResult.addProcessingStep(aeReportId, " " + rdWrapper.getReadableMessage(), null);
            }
        }

        if (!rdAmmendSet.isEmpty()) {
            evaluationResult.addProcessingStep(aeReportId, "caAERS: Amend options :", null);
            for (ReportDefinitionWrapper rdWrapper : rdAmmendSet) {
                evaluationResult.addProcessingStep(aeReportId, " " + rdWrapper.getReadableMessage(), null);
            }
        }

        if (!rdEditSet.isEmpty()) {
            evaluationResult.addProcessingStep(aeReportId, "caAERS: Edit options :", null);
            for (ReportDefinitionWrapper rdWrapper : rdEditSet) {
                evaluationResult.addProcessingStep(aeReportId, " " + rdWrapper.getReadableMessage(), null);
            }
        }

        if (!rdWithdrawSet.isEmpty()) {
            evaluationResult.addProcessingStep(aeReportId, "caAERS: Withdraw options :", null);
            for (ReportDefinitionWrapper rdWrapper : rdWithdrawSet) {
                evaluationResult.addProcessingStep(aeReportId, " " + rdWrapper.getReadableMessage(), null);
            }
        }

        //update the result object
        evaluationResult.addEvaluatedAdverseEvents(aeReportId, evaluatableAeList);
        //           evaluationResult.addResult(aeList, reportDefinitions);
        evaluationResult.addResult(expeditedData, reportDefinitions);

    } catch (Exception e) {
        throw new CaaersSystemException(
                "Could not determine the reports necessary for the given expedited adverse event data", e);
    }

}

From source file:de.unihannover.l3s.mws.bean.SearchAll.java

public void loadSearch(Long id) {
    id = Long.parseLong(this.resultId);
    if (id != 0) {

        RicercaDao rd = new RicercaDao();
        Ricerca ric = rd.getRicercaById(id);
        this.r = ric;
        this.name = ric.getNome();
        try {//w ww .j a va 2  s . c  o  m

            TrackDao td = new TrackDao();
            Track track = new Track();
            Calendar c = new GregorianCalendar();
            track.setDate(c.getTime());
            track.setOperation("load_search");
            track.setParam1(this.name);
            track.setUtente(this.user.getUtente());
            td.addTrack(track);

            JSONObject avList = new JSONObject(ric.getSiteAvailablelists());
            JSONArray arr1 = (JSONArray) avList.get("siteAvailablelist1");
            this.siteAvailablelist1 = new ArrayList<String>();
            for (int i = 0; i < arr1.length(); i++)
                this.siteAvailablelist1.add(arr1.get(i).toString());

            arr1 = (JSONArray) avList.get("siteAvailablelist2");
            this.siteAvailablelist2 = new ArrayList<String>();
            for (int i = 0; i < arr1.length(); i++)
                this.siteAvailablelist2.add(arr1.get(i).toString());

            arr1 = (JSONArray) avList.get("siteAvailablelist3");
            this.siteAvailablelist3 = new ArrayList<String>();
            for (int i = 0; i < arr1.length(); i++)
                this.siteAvailablelist3.add(arr1.get(i).toString());

            JSONObject slList = new JSONObject(ric.getSiteSelectedlists());
            arr1 = (JSONArray) slList.get("siteSelectedlist1");
            this.siteSelectedlist1 = new ArrayList<String>();
            for (int i = 0; i < arr1.length(); i++)
                this.siteSelectedlist1.add(arr1.get(i).toString());

            arr1 = (JSONArray) slList.get("siteSelectedlist2");
            this.siteSelectedlist2 = new ArrayList<String>();
            for (int i = 0; i < arr1.length(); i++)
                this.siteSelectedlist2.add(arr1.get(i).toString());

            arr1 = (JSONArray) slList.get("siteSelectedlist3");
            this.siteSelectedlist3 = new ArrayList<String>();
            for (int i = 0; i < arr1.length(); i++)
                this.siteSelectedlist3.add(arr1.get(i).toString());

            JSONObject stList = new JSONObject(ric.getSearchterms());
            arr1 = (JSONArray) stList.get("searchTerms");
            this.searchterms = new ArrayList<String>();
            for (int i = 0; i < arr1.length(); i++)
                this.searchterms.add(arr1.get(i).toString());

            JSONObject dpList = new JSONObject(ric.getSearchDataPies());
            this.searchDataPie1 = dpList.get("searchDataPie1").toString();
            this.searchDataPie2 = dpList.get("searchDataPie2").toString();
            this.searchDataPie3 = dpList.get("searchDataPie3").toString();

            JSONObject WdpList = new JSONObject(ric.getSearchWeightedDataPies());
            this.searchWeightedDataPie1 = WdpList.get("searchWeightedPie1").toString();

            JSONObject DdpList = new JSONObject(ric.getSearchDomainDataPies());
            this.searchLangDataPie1 = DdpList.get("searchDomainPie1").toString();

            searchResultWeb = new ArrayList<SearchResult>();
            searchResultVideo = new ArrayList<SearchResult>();
            searchResultImg = new ArrayList<SearchResult>();

            List<String> exclude1 = new ArrayList<String>(siteAvailablelist1);
            exclude1.removeAll(siteSelectedlist1);

            List<String> exclude2 = new ArrayList<String>(siteAvailablelist2);
            exclude2.removeAll(siteSelectedlist2);

            List<String> exclude3 = new ArrayList<String>(siteAvailablelist3);
            exclude3.removeAll(siteSelectedlist3);

            teasers = new ArrayList<String>();
            for (Risultati r : ric.getRisultati()) {
                JSONObject ris = new JSONObject(r.getRisultato());

                if (r.getType().equals("WEB")) {
                    SearchWebResult rweb = new SearchWebResult();
                    rweb.setTitle(ris.getString("title"));
                    rweb.setDescription(ris.getString("description"));
                    teasers.add(ris.getString("description"));
                    rweb.setUrl(ris.getString("url"));
                    searchResultWeb.add(rweb);
                }
                if (r.getType().equals("VIDEO")) {
                    SearchVideoResult rvideo = new SearchVideoResult();
                    rvideo.setTitle(ris.getString("title"));
                    rvideo.setRuntime(ris.getString("runtime"));
                    JSONObject thumbnail = (JSONObject) ris.get("thumbnail");
                    BingThumbnail bt = new BingThumbnail();
                    if (thumbnail.has("fileSize"))
                        bt.setFileSize(thumbnail.getLong("fileSize"));
                    if (thumbnail.has("height"))
                        bt.setHeight(thumbnail.getInt("height"));
                    if (thumbnail.has("mediaUrl"))
                        bt.setMediaUrl(thumbnail.getString("mediaUrl"));
                    if (thumbnail.has("width"))
                        bt.setHeight(thumbnail.getInt("width"));
                    if (thumbnail.has("contentType"))
                        bt.setContentType(thumbnail.getString("contentType"));
                    rvideo.setThumbnail(bt);
                    if (ris.has("url"))
                        rvideo.setUrl(ris.getString("url"));
                    else
                        System.out.println("SENZA URL : " + r.getId());
                    searchResultVideo.add(rvideo);
                }
                if (r.getType().equals("IMAGE")) {
                    SearchImageResult rimg = new SearchImageResult();
                    rimg.setTitle(ris.getString("title"));
                    if (ris.has("height"))
                        rimg.setHeight(ris.getInt("height"));
                    if (ris.has("width"))
                        rimg.setWidth(ris.getInt("width"));
                    if (ris.has("url"))
                        rimg.setUrl(ris.getString("url"));
                    searchResultImg.add(rimg);
                }
            }
            searchResult1 = new ArrayList<SearchResult>(searchResultWeb);
            ArrayList<SearchResult> toremove = new ArrayList<SearchResult>();
            for (SearchResult res : searchResult1) {
                for (String exc : exclude1)
                    if (res.getUrl().contains(exc))
                        toremove.add(res);
            }
            for (SearchResult sr : toremove)
                searchResult1.remove(sr);

            searchResult2 = new ArrayList<SearchResult>(searchResultVideo);
            toremove = new ArrayList<SearchResult>();
            for (SearchResult res : searchResult2) {
                for (String exc : exclude2)
                    if (res.getUrl().contains(exc))
                        toremove.add(res);
            }
            for (SearchResult sr : toremove)
                searchResult2.remove(sr);

            searchResult3 = new ArrayList<SearchResult>(searchResultImg);
            toremove = new ArrayList<SearchResult>();
            for (SearchResult res : searchResult3) {
                for (String exc : exclude3)
                    if (res.getUrl().contains(exc))
                        toremove.add(res);
            }
            for (SearchResult sr : toremove)
                searchResult3.remove(sr);

            StatsManager sm = new StatsManager();
            List<YData> Llist = sm.getMatcthTable(sm.getLangSites(searchResult1, null, null));

            searchLangDataPie1 = "var langdata = [ ";
            List<String> datastring = new ArrayList<String>();
            for (YData a : Llist) {
                datastring.add("{ label: \"" + a.getSite() + "\", data: " + a.getQty() + "} ");
            }
            searchLangDataPie1 += Joiner.on(",").join(datastring);
            searchLangDataPie1 += " ]; ";
            searchLangDataPie1 += "$.plot($(\"#chartlangpie1\"), langdata, options ); \n";
            String hoverL = " $(\"#chartlangpie1\").bind(\"plothover\", function(event, pos, obj){ if (!obj){return;} percent = parseFloat(obj.series.percent).toFixed(2); var html = []; html.push(\"<div style=\\\"flot:left;width:105px;height:20px;text-align:center;border:0px solid black; \\\">\", \"<span style=\\\"font-weight:bold;color:red\\\">\", obj.series.label, \" (\", percent, \"%)</span>\", \"</div>\"); $(\"#showInteractive1L\").html(html.join('')); }); ";
            searchLangDataPie1 += hoverL;
            String plotclickL = " $(\"#chartlangpie1\").bind(\"plotclick\", function(event, pos, obj){ if (!obj){return;} }); ";
            searchLangDataPie1 += plotclickL;
            searchLangDataPie1 += " var choiceContainerL = $(\"#chartlangpie1\");";
            searchLangDataPie1 += " choiceContainerL.find(\"input\").click(plotAccordingToChoicesL);";
            searchLangDataPie1 += " function plotAccordingToChoicesL() { ";
            searchLangDataPie1 += " var key = $(this).attr(\"name\"); ";
            searchLangDataPie1 += " $( \"input[value*='\"+key+\"']\" ).trigger('click'); ";
            searchLangDataPie1 += " }";
            searchLangDataPie1 += "  ";
            alignSiteDomain();

            this.resultId = "0";
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    // return "basicSearch";
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.doseresponse.area.AreaDRResultsController.java

/**
 * Create PdfTable with info on each condition of the analysis group;
 *
 * @return//from   w  w w.  j a v a 2s.  co  m
 */
//possibly reuse dRInputController's createTableModel(List<PlateCondition> processedConditions)
@Override
protected PdfPTable createAnalysisGroupInfoTable() {
    //maps log transformed conc (double) to list of velocities (double)
    List<DoseResponsePair> fittedData = doseResponseController.getDataToFit(false);
    //CONTROL HAS BEEN GIVEN A CONCENTRATION FOR FITTING PURPOSES: find control concentration (lowest)
    List<Double> allConcentrations = new ArrayList<>();
    for (DoseResponsePair row : fittedData) {
        allConcentrations.add(row.getDose());
    }
    Double controlConcentration = Collections.min(allConcentrations);

    // new table with 6 columns
    PdfPTable dataTable = new PdfPTable(6);
    PdfUtils.setUpPdfPTable(dataTable);
    // add 1st row: column names
    PdfUtils.addCustomizedCell(dataTable, "DRUG CONCENTRATION", boldFont);
    PdfUtils.addCustomizedCell(dataTable, "# TECHNICAL REPLICATES", boldFont);
    PdfUtils.addCustomizedCell(dataTable, "TECHNICAL REPLICATES EXCLUDED?", boldFont);
    PdfUtils.addCustomizedCell(dataTable, "LOWEST VELOCITY", boldFont);
    PdfUtils.addCustomizedCell(dataTable, "HIGHEST VELOCITY", boldFont);
    PdfUtils.addCustomizedCell(dataTable, "MEDIAN VELOCITY", boldFont);

    // for each condition get results and add a cell
    for (DoseResponsePair condition : fittedData) {
        Integer replicates = condition.getResponses().size();
        String excluded;
        int excludedCount = 0;
        List<Double> velocities = condition.getResponses();

        //count how many replicates were excluded
        for (int i = 0; i < velocities.size(); i++) {
            Double replicate = velocities.get(i);
            if (replicate == null) {
                excludedCount++;
            }
        }
        if (excludedCount == 0) {
            excluded = "NO";
        } else {
            excluded = "YES, " + excludedCount;
        }

        //put log-value of the concentration back to an understandable format
        String concentration;
        Double logConc = condition.getDose();
        Double transformed = Math.pow(10, logConc);
        //check which concentration unit is to be used
        //if lower than 0.1 M: use nM unit
        if (transformed < Math.pow(10, -7)) {
            concentration = AnalysisUtils.roundTwoDecimals(transformed * Math.pow(10, 9)) + " nM";
        } //if lower than 0.1 mM: use M unit
        else if (transformed < Math.pow(10, -3)) {
            concentration = AnalysisUtils.roundTwoDecimals(transformed * Math.pow(10, 6)) + " M";
        } //else for everything >= 1 mM use mM unit
        else {
            concentration = AnalysisUtils.roundTwoDecimals(transformed * Math.pow(10, 3)) + " mM";
        }
        //if this is the control, replace concentration string
        if (logConc.equals(controlConcentration)) {
            concentration = "Control";
        }
        //remove null's (excluded replicates) from velocities collection
        velocities.removeAll(Collections.singleton(null));

        PdfUtils.addCustomizedCell(dataTable, concentration, bodyFont);
        PdfUtils.addCustomizedCell(dataTable, replicates.toString(), bodyFont);
        PdfUtils.addCustomizedCell(dataTable, excluded, bodyFont);
        PdfUtils.addCustomizedCell(dataTable,
                AnalysisUtils.roundThreeDecimals(Collections.min(velocities)).toString(), bodyFont);
        PdfUtils.addCustomizedCell(dataTable,
                AnalysisUtils.roundThreeDecimals(Collections.max(velocities)).toString(), bodyFont);
        PdfUtils.addCustomizedCell(dataTable,
                AnalysisUtils.roundThreeDecimals(AnalysisUtils.computeMedian(velocities)).toString(), bodyFont);

    }

    return dataTable;
}

From source file:com.vmware.bdd.service.impl.ClusteringService.java

/**
 * cluster create, resize, resume will all call this method for static ip
 * allocation the network contains all allocated ip address to this cluster,
 * so some of them may already be occupied by existing node. So we need to
 * detect if that ip is allocated, before assign that one to one node
 *
 * @param vNodes/*  www  .j  av a 2  s.  c o  m*/
 * @param networkAdds
 * @param occupiedIpSets
 */
private void allocateStaticIp(List<BaseNode> vNodes, List<NetworkAdd> networkAdds,
        Map<String, Set<String>> occupiedIpSets) {
    int i, j;
    for (i = 0; i < networkAdds.size(); i++) {
        NetworkAdd networkAdd = networkAdds.get(i);
        String portGroupName = networkAdd.getPortGroup();
        Set<String> usedIps = null;
        if (occupiedIpSets != null && !occupiedIpSets.isEmpty()) {
            usedIps = occupiedIpSets.get(portGroupName);
        }

        if (networkAdd.getIsDhcp()) {
            // no need to allocate ip for dhcp
            logger.info("using dhcp for network: " + portGroupName);
        } else {
            logger.info("Start to allocate static ip address for each VM's " + i + "th network.");
            List<String> availableIps = IpBlock.getIpAddressFromIpBlock(networkAdd.getIpBlocks());
            if (usedIps != null && !usedIps.isEmpty()) {
                availableIps.removeAll(usedIps);
            }
            AuAssert.check(availableIps.size() == vNodes.size());
            for (j = 0; j < availableIps.size(); j++) {
                vNodes.get(j).updateNicOfPortGroup(portGroupName, availableIps.get(j), null, null);
            }
            logger.info("Finished to allocate static ip address for VM's mgr network.");
        }
    }
}

From source file:io.personium.core.model.impl.fs.DavCmpFsImpl.java

/**
 * ID?URL?./*www.j a v  a  2  s. c  o  m*/
 * jsonObj?IDURL???
 * @param jsonObj
 *            ID??JSON
 * @param baseUrlStr
 *            xml:base
 */
private Acl roleIdToName(Object jsonObj, String baseUrlStr) {
    Acl ret = Acl.fromJson(((JSONObject) jsonObj).toJSONString());
    List<Ace> aceList = ret.getAceList();
    if (aceList == null) {
        return ret;
    }
    // xml:base
    List<Ace> eraseList = new ArrayList<>();
    for (Ace ace : aceList) {
        String pHref = ace.getPrincipalHref();
        if (pHref != null) {
            // ID????????????????
            String roloResourceUrl = this.cell.roleIdToRoleResourceUrl(pHref);
            log.debug("###" + pHref + ":" + roloResourceUrl);
            if (roloResourceUrl == null) {
                eraseList.add(ace);
                continue;
            }
            // base:xml?URL?
            roloResourceUrl = baseUrlToRoleResourceUrl(baseUrlStr, roloResourceUrl);
            ace.setPrincipalHref(roloResourceUrl);
        }
    }
    aceList.removeAll(eraseList);
    ret.setBase(baseUrlStr);
    return ret;
}

From source file:com.linkedin.pinot.controller.helix.core.PinotHelixResourceManager.java

private PinotResourceManagerResponse updateColocatedServerTenant(Tenant serverTenant,
        PinotResourceManagerResponse res, String realtimeServerTag, List<String> taggedRealtimeServers,
        String offlineServerTag, List<String> taggedOfflineServers, int incInstances,
        List<String> unTaggedInstanceList) {
    int incOffline = serverTenant.getOfflineInstances() - taggedOfflineServers.size();
    int incRealtime = serverTenant.getRealtimeInstances() - taggedRealtimeServers.size();
    taggedRealtimeServers.removeAll(taggedOfflineServers);
    taggedOfflineServers.removeAll(taggedRealtimeServers);
    for (int i = 0; i < incOffline; ++i) {
        if (i < incInstances) {
            retagInstance(unTaggedInstanceList.get(i), CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE,
                    offlineServerTag);// ww  w .j a v a 2  s. c  o m
        } else {
            _helixAdmin.addInstanceTag(_helixClusterName, taggedRealtimeServers.get(i - incInstances),
                    offlineServerTag);
        }
    }
    for (int i = incOffline; i < incOffline + incRealtime; ++i) {
        if (i < incInstances) {
            retagInstance(unTaggedInstanceList.get(i), CommonConstants.Helix.UNTAGGED_SERVER_INSTANCE,
                    realtimeServerTag);
            // TODO: update idealStates & instanceZkMetadata
        } else {
            _helixAdmin.addInstanceTag(_helixClusterName,
                    taggedOfflineServers.get(i - Math.max(incInstances, incOffline)), realtimeServerTag);
            // TODO: update idealStates & instanceZkMetadata
        }
    }
    res.status = ResponseStatus.success;
    return res;
}

From source file:com.novartis.opensource.yada.test.ServiceTest.java

/**
 * Combines the queries from multiple resources into a single array to
 * facilitate execution of tests from multiple files
 * /*  w w w .j  a v a2s.  c  om*/
 * @param paths the paths to the test scripts
 * @return an array of query or JSON strings
 * @throws URISyntaxException when a handle can't be attached to the test file
 *         path
 * @throws IOException if the {@link InputStream} used for reading test files
 *         can't be closed
 */
public String[] mergeArrays(String[] paths) throws URISyntaxException, IOException {
    String engine = ConnectionFactoryTest.getProps().getProperty("jdbc.engine");
    String[] params = null;
    for (int i = 0; i < paths.length; i++) {
        params = (String[]) ArrayUtils.addAll(params, loadResource(paths[i]));

        if (engine != null) {
            String enginePath = paths[i].replace(".txt", "_" + engine + ".txt");
            String[] engineResources = loadResource(enginePath);
            if (engineResources != null)
                params = (String[]) ArrayUtils.addAll(params, engineResources);
        }
    }
    List<String> list = new ArrayList<>(Arrays.asList(params));
    List<String> comments = new ArrayList<>();
    for (String entry : list) {
        if (isComment(entry) || entry.length() == 0) {
            comments.add(entry);
        }
    }
    list.removeAll(comments);
    params = list.toArray(new String[list.size()]);

    return params;
}

From source file:se.gothiaforum.controller.tagcloud.TagCloudController.java

/**
 * Renders the view for the tag cloud.//from   ww  w. ja  v a 2 s. com
 * 
 * @param request
 *            the request
 * @param model
 *            the model
 * @return a view
 */
@RenderMapping
public String renderView(RenderRequest request, Model model) {

    try {

        List<JournalArticle> articles = JournalArticleLocalServiceUtil.getJournalArticles(0,
                JournalArticleLocalServiceUtil.getJournalArticlesCount());

        Set<AssetEntry> entrys = new HashSet<AssetEntry>();

        for (JournalArticle ja : articles) {
            if (ja.getType().equals(ActorsConstants.TYPE_ACTOR)) {
                entrys.add(AssetEntryLocalServiceUtil.getEntry(JournalArticle.class.getName(),
                        ja.getResourcePrimKey()));
            }
        }

        Multiset<AssetTag> tagMultiSet = HashMultiset.create();

        for (AssetEntry entry : entrys) {

            List<AssetTag> tags = AssetTagLocalServiceUtil.getEntryTags(entry.getEntryId());

            for (AssetTag tag : tags) {
                tagMultiSet.add(tag);
            }
        }

        List<TagVO> tagVOList = new ArrayList<TagVO>();

        for (Entry<AssetTag> entry : tagMultiSet.entrySet()) {

            String cssClass;

            final int number8 = 8;
            final int number7 = 7;
            final int number6 = 6;
            final int number5 = 5;
            final int number4 = 4;
            final int number3 = 3;
            final int number2 = 2;

            if (entry.getCount() > number8) {
                cssClass = "tag-weight-10";
            } else if (entry.getCount() > number7) {
                cssClass = "tag-weight-9";
            } else if (entry.getCount() > number6) {
                cssClass = "tag-weight-8";
            } else if (entry.getCount() > number5) {
                cssClass = "tag-weight-7";
            } else if (entry.getCount() > number4) {
                cssClass = "tag-weight-6";
            } else if (entry.getCount() > number3) {
                cssClass = "tag-weight-5";
            } else if (entry.getCount() > number2) {
                cssClass = "tag-weight-4";
            } else {
                cssClass = "tag-weight-2";
            }

            TagVO tagVO = new TagVO(cssClass, entry.getElement().getName(),
                    ActorsConstants.SEARCH_REDIRECT_URL + entry.getElement().getName(),
                    entry.getElement().getTagId());

            tagVO.setCount(entry.getCount());

            tagVOList.add(tagVO);

        }

        final int size = 20;

        if (tagVOList.size() > size) {

            for (int i = 1; tagVOList.size() > size; i++) {

                List<TagVO> removeList = new ArrayList<TagVO>();

                for (TagVO tagVO : tagVOList) {

                    if (tagVO.getCount() == i) {
                        removeList.add(tagVO);
                    }
                }
                tagVOList.removeAll(removeList);
            }
        }

        Collections.shuffle(tagVOList);

        model.addAttribute("tagVOList", tagVOList);

    } catch (SystemException e) {
        e.printStackTrace();
    } catch (PortalException e) {
        e.printStackTrace();
    }

    return "tagCloudView";
}