List of usage examples for org.apache.commons.collections15 Closure Closure
Closure
From source file:gov.nih.nci.cabig.caaers.domain.ResearchStaff.java
/** * Will copy into this Person, the details from the input Person. * * @param rs - The Person from which the details to be copied from. *//*from www. ja v a 2s. com*/ public void sync(final ResearchStaff rs) { super.sync(rs); setNciIdentifier(rs.getNciIdentifier()); if (getAddress() != null) { getAddress().sync(rs.getAddress()); } else { setAddress(rs.getAddress()); } //sync the site researchstaffs CollectionUtils.forAllDo(getSiteResearchStaffs(), new Closure<SiteResearchStaff>() { public void execute(SiteResearchStaff srs) { SiteResearchStaff otherSRS = rs.findSiteResearchStaff(srs); srs.sync(otherSRS); } }); //add new site researchstaff if needed for (SiteResearchStaff srs : rs.getSiteResearchStaffs()) { SiteResearchStaff availableSRS = findSiteResearchStaff(srs); if (availableSRS == null) addSiteResearchStaff(srs); } }
From source file:com.diversityarrays.dal.server.ServerGui.java
private void ensureDatabaseInitialisedThenStartServer() { try {//from ww w. j a v a2 s . c om DalDatabase db = server.getDalDatabase(); if (db.isInitialiseRequired()) { try { Closure<String> progress = new Closure<String>() { @Override public void execute(String msg) { messages.append(msg + "\n"); } }; db.initialise(progress); } catch (DalDbException e) { GuiUtil.errorMessage(ServerGui.this, e, "Unable to initialise database: " + db.getDatabaseName()); } } System.out.println("Session Auto-Expiry after " + server.getMaxInactiveMinutes() + " minutes"); NanoHTTPD httpServer = server.getHttpServer(); String hostPort = httpServer.getHostname() + ":" + httpServer.getPort(); System.out.println("Starting server: " + hostPort); IOException err = ServerRunner.executeInstance(httpServer, false); if (err != null) { serverStartAction.setEnabled(true); if (err instanceof java.net.BindException) { System.err.println("!!!! " + hostPort + ": " + err.getMessage()); } else { System.err.println("!!!! " + err.getMessage()); err.printStackTrace(); } } } catch (Exception e) { GuiUtil.errorMessage(ServerGui.this, e, "Server Start Failed"); } }
From source file:com.diversityarrays.kdxplore.field.FieldViewPanel.java
/** * Create a new FieldViewPanel using the caller-provided VisitOrder2D and PlotsPerGroup. * @param database// w w w . ja v a 2 s . c o m * @param trial * @param visitOrder * @param plotsPerGroup * @return * @throws IOException */ public static FieldViewPanel create(KDSmartDatabase database, Trial trial, VisitOrder2D visitOrder, PlotsPerGroup plotsPerGroup, SimplePlotCellRenderer plotRenderer, SeparatorVisibilityOption visibilityOption, Component... extras) throws IOException { Map<WhyMissing, List<String>> missing = new TreeMap<>(); Closure<Pair<WhyMissing, MediaFileRecord>> reportMissing = new Closure<Pair<WhyMissing, MediaFileRecord>>() { @Override public void execute(Pair<WhyMissing, MediaFileRecord> pair) { WhyMissing why = pair.first; MediaFileRecord mfr = pair.second; List<String> list = missing.get(why); if (list == null) { list = new ArrayList<>(); missing.put(why, list); } list.add(mfr.getFilePath()); } }; int trialId = trial.getTrialId(); Map<Integer, Plot> plotById = DatabaseUtil.collectPlotsIncludingMediaFiles(database, trialId, "FieldViewPanel", SampleGroupChoice.ANY_SAMPLE_GROUP, reportMissing); List<Plot> plots = new ArrayList<>(plotById.values()); if (!missing.isEmpty()) { SwingUtilities.invokeLater(new Runnable() { public void run() { StringBuilder html = new StringBuilder("<HTML><DL>"); for (WhyMissing why : missing.keySet()) { html.append("<DT>").append(why.name()).append("</DT><DD>"); List<String> list = missing.get(why); if (list.size() == 1) { html.append(StringUtil.htmlEscape(list.get(0))); } else { html.append("<UL>"); for (String s : list) { html.append("<LI>").append(StringUtil.htmlEscape(s)).append("</LI>"); } html.append("</UL>"); } html.append("</DD>"); } html.append("</DL>"); MsgBox.warn(null, html.toString(), "Missing Files"); } }); } Map<Integer, Trait> traitMap = new HashMap<>(); database.getTrialTraits(trialId).stream().forEach(t -> traitMap.put(t.getTraitId(), t)); List<TraitInstance> traitInstances = new ArrayList<>(); Predicate<TraitInstance> traitInstanceVisitor = new Predicate<TraitInstance>() { @Override public boolean evaluate(TraitInstance ti) { traitInstances.add(ti); return true; } }; database.visitTraitInstancesForTrial(trialId, KDSmartDatabase.WithTraitOption.ALL_WITH_TRAITS, traitInstanceVisitor); PlotVisitList plotVisitList = buildPlotVisitList(trial, visitOrder, plotsPerGroup, traitMap, traitInstances, plots); if (plotRenderer == null) { plotRenderer = new SimplePlotCellRenderer(); } return new FieldViewPanel(plotVisitList, traitMap, visibilityOption, plotRenderer, extras); }
From source file:gov.nih.nci.cabig.caaers.web.ae.AbstractExpeditedAdverseEventInputCommand.java
/** * Will update the mandatory fields details. * 1. Evaluate the mandatory-ness via EvaluationService * 2. Update the mandatory properties./*from ww w . j av a2 s. com*/ * 3. Update the rendering decisions */ public void updateFieldMandatoryness() { //figureout the reports List<Report> reportsToEvaluate = new ArrayList<Report>(); for (ReportDefinition rd : getSelectedReportDefinitions()) { reportsToEvaluate.add(rd.createReport()); } mandatoryProperties = new MandatoryProperties(expeditedReportTree); //evaluate the mandatoryness CollectionUtils.forAllDo(reportsToEvaluate, new Closure<Report>() { public void execute(Report report) { evaluationService.evaluateMandatoryness(aeReport, report); for (ReportMandatoryField mf : report.getMandatoryFields()) { Mandatory mandatoryness = mf.getMandatory(); if (mandatoryness == Mandatory.MANDATORY) { if (mf.isSelfReferenced()) { mandatoryProperties.addRealPropertyPath(mf.getFieldPath()); } else { mandatoryProperties.addNode(mf.getFieldPath()); } } } } }); //update the render decision renderDecisionManager.updateRenderDecision(reportsToEvaluate); }
From source file:com.diversityarrays.kdxplore.trialmgr.TrialManagerApp.java
@Override public AfterUpdateResult initialiseAppAfterUpdateCheck(AppInitContext initContext) { final AfterUpdateResult[] initResult = new AfterUpdateResult[1]; initResult[0] = AfterUpdateResult.OK; trialExplorerPanel.doPostOpenOperations(); String currentDatabaseUrl = explorerProperties.getCurrentDatabaseUrl(); if (!KdxploreDatabase.LOCAL_DATABASE_URL.equalsIgnoreCase(currentDatabaseUrl)) { clientProvider.setInitialClientUrl(currentDatabaseUrl); }/*from w w w . ja va2s. co m*/ clientProvider.setInitialClientUsername(explorerProperties.getCurrentDatabaseUsername()); if (currentDatabaseUrl == null) { currentDatabaseUrl = KdxploreDatabase.LOCAL_DATABASE_URL; } Closure<DatabaseDataLoadResult> loadDataErrorCompleteHandler = new Closure<DatabaseDataLoadResult>() { @Override public void execute(DatabaseDataLoadResult result) { Throwable problem = result.cause; if (problem == null) { // If user is logged in it may be to another database // so ensure we don't get confused by shutting down the extant connection. if (clientProvider.isClientAvailable()) { DALClient client = clientProvider.getDALClient(); if (!client.getBaseUrl().equalsIgnoreCase(result.dbUrl)) { clientProvider.logout(); } } String initialTabName = TAB_TRIALS; if (KdxploreConfig.getInstance().getModeList().contains("CIMMYT") && trialExplorerPanel.getTrialCount() <= 0 && traitExplorerPanel.getTraitCount() <= 0) { // This will suggest that the user loads traits first. initialTabName = TAB_TRAITS; // The reason for this in CIMMYT mode is that because the // user isn't able to get the Traits from the database // they really should load the Traits first. // } int index = tabbedPane.indexOfTab(initialTabName); tabbedPane.setSelectedIndex(index); } else { problem.printStackTrace(); messagesPanel.println(problem); Throwable lastCause = null; Throwable cause = problem; while (cause != null) { lastCause = cause; cause = cause.getCause(); } if (lastCause != null) { Shared.Log.e(TAG, "Initialisation Failed", lastCause); //$NON-NLS-1$ } // Replace all extant tabs with the Error tab. for (int tabIndex = tabbedPane.getTabCount(); --tabIndex >= 0;) { tabbedPane.remove(tabIndex); } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); result.cause.printStackTrace(pw); pw.close(); JTextArea ta = new JTextArea(sw.toString()); ta.setEditable(false); tabbedPane.addTab(Msg.TAB_INIT_ERROR(), new JScrollPane(ta)); initResult[0] = AfterUpdateResult.FAIL_IF_ALL; String errmsg = lastCause == null ? "" : lastCause.getMessage(); //$NON-NLS-1$ GuiUtil.errorMessage(TrialManagerApp.this, Msg.ERRMSG_CHECK_MESSSAGES_URL_CAUSE(result.dbUrl, errmsg), OfflineData.LOADING_OFFLINE_REFERENCE_DATA_ERROR()); } } }; List<DatabaseDataStub> databaseStubs = DatabaseDataUtils.collectDatabaseDirectories(userDataFolder, driverType); DatabaseDataStub chosen = null; if (databaseStubs.isEmpty()) { // This is a brand new one. chosen = DatabaseDataStub.create(driverType, userDataFolder, currentDatabaseUrl); // Path dirPath = Paths.get(defaultKdxploreDatabaseLocation.databaseDirectory.getPath()); // boolean isDefaultDatabase = defaultKdxploreDatabaseLocation.databaseDirectory.equals(dirPath.toFile()); // chosen = new DatabaseDataStub(isDefaultDatabase, defaultKdxploreDatabaseLocation.driverType, dirPath, currentDatabaseUrl, null); } else { if (databaseStubs.size() == 1) { chosen = databaseStubs.get(0); } else { DatabaseDataStub[] selectionValues = databaseStubs .toArray(new DatabaseDataStub[databaseStubs.size()]); for (DatabaseDataStub dds : selectionValues) { if (currentDatabaseUrl.equalsIgnoreCase(dds.dburl)) { chosen = dds; break; } } if (chosen == null) { chosen = selectionValues[0]; } Object answer = JOptionPane.showInputDialog(TrialManagerApp.this, Msg.MSG_CHOOSE_DATABASE_TO_OPEN_DEFAULT(chosen.toString()), Msg.TITLE_MULTIPLE_DATABASES_FOUND(), JOptionPane.QUESTION_MESSAGE, null, selectionValues, chosen); if (answer instanceof DatabaseDataStub) { chosen = (DatabaseDataStub) answer; } } } if (chosen == null) { initResult[0] = AfterUpdateResult.FAIL_IF_ALL; // System.exit(0); } else { loadOfflineDataAsync(chosen, loadDataErrorCompleteHandler); trialExplorerPanel.initialiseUploadHandler(offlineData); } return initResult[0]; }
From source file:com.diversityarrays.kdxplore.trials.TrialExplorerPanel.java
private void doCollectTrialInfoAfterClientCheck(final Trial trial) { Closure<TrialLoadResult> onFinish = new Closure<TrialLoadResult>() { @Override/*w w w. j a va 2s .c om*/ public void execute(TrialLoadResult lr) { handleTrialDataLoadResult(EDIT_TRIAL, lr); } }; collectTrialInfoAfterClientCheck(EDIT_TRIAL, trial, onFinish); }
From source file:com.diversityarrays.kdxplore.trials.TrialExplorerPanel.java
private void askForTrialsThenDownload(DALClient client) { try {//from w w w .ja v a 2 s.co m Transformer<BackgroundRunner, TrialSearchOptionsPanel> searchOptionsPanelFactory = new Transformer<BackgroundRunner, TrialSearchOptionsPanel>() { @Override public TrialSearchOptionsPanel transform(BackgroundRunner br) { return TrialSelectionSearchOptionsPanel.create(br); } }; final TrialSelectionDialog trialSelectionDialog = new TrialSelectionDialog( GuiUtil.getOwnerWindow(TrialExplorerPanel.this), "Choose Trials to Download", client, offlineData.getTrials(), searchOptionsPanelFactory); trialSelectionDialog.setVisible(true); if (trialSelectionDialog.trialRecords != null) { Closure<TrialLoaderResult> onTrialsAdded = new Closure<TrialLoaderResult>() { @Override public void execute(TrialLoaderResult trialLoaderResult) { handleTrialDataLoaded(trialLoaderResult); } }; boolean wantSpecimens = getSpecimensRequired(); Exception error = null; Optional<Optional<GeneralType>> opt_opt_mmt = Optional.empty(); try { opt_opt_mmt = MediaSampleRetriever.getCuratedSamplesMultimediaType(TrialExplorerPanel.this, offlineData.getKddartReferenceData()); } catch (MultimediaSourceMissingException e) { error = e; } if (!opt_opt_mmt.isPresent()) { MediaSampleRetriever.showMissingMultimedia(TrialExplorerPanel.this, error, "Can't upload"); return; } MultiTrialLoader multiTrialLoader = new MultiTrialLoader(TrialExplorerPanel.this, "Saving Trials for Offline access", true, client, dartSchemaHelper, wantSpecimens, pluginInfo.getBackgroundRunner(), pluginInfo.getBackgroundRunner(), pluginInfo.getMessageLogger(), offlineData.getKdxploreDatabase(), opt_opt_mmt.get(), DEFAULT_DOWNLOAD_TRAIT_NAME_STYLE, trialSelectionDialog.trialRecords, onTrialsAdded); backgroundRunner.runBackgroundTask(multiTrialLoader); } } catch (IOException e) { MsgBox.error(TrialExplorerPanel.this, e.getMessage(), "Problem Getting Trials"); } }
From source file:com.diversityarrays.kdxplore.trials.TrialExplorerPanel.java
private void loadFromKddartDatabase() { try {/*from w w w.ja v a2s . c o m*/ List<Trial> trialList = offlineData.getTrials(); DALClient client = null; // clientUrlChanger.setIgnoreClientUrlChanged(true); // FIXME - move this code out of trialmgr into the OfflineDataApp // so that it is all managed centrally. // This will mean changes to the places that track the URL. // SHould probably also move the Offfline data management to that // KdxApp too. client = clientProvider.getDALClient(ADD_TRIALS); if (client == null) { return; // user cancelled } final UrlChangeConfirmation confirmation = confirmChangedClientIsOk(client, ADD_TRIALS, WILL_NOT_CANCEL_PENDING); switch (confirmation) { case CHANGE_DENIED: return; case NEW_DATABASE: case CHANGE_APPROVED: initClientLog(client); Closure<DALClient> onLoadComplete = new Closure<DALClient>() { @Override public void execute(DALClient dalClient) { clientUrlChanger.clientUrlChanged(); if (dalClient == null) { Shared.Log.w(TAG, "loadFromKddartDatabase: " + ADD_TRIALS //$NON-NLS-1$ + ": Failed to change client"); //$NON-NLS-1$ } else { askForTrialsThenDownload(dalClient); } } }; loadDatabaseDataFromKddart(ADD_TRIALS, confirmation, client, onLoadComplete); break; case NO_CHANGE_SAME_URL: initClientLog(client); doAddTrials(client, trialList); break; default: throw new RuntimeException("Unhandled value " + confirmation); } } catch (IOException err) { MsgBox.error(TrialExplorerPanel.this, err.getMessage(), "Problem Getting Trials"); } }
From source file:com.diversityarrays.kdxplore.trials.TrialExplorerPanel.java
private void retrieveTrialDataFromServer(Trial trial, boolean newTrials) { if (!autoUpdate) { throw new RuntimeException("Not auto-updating not yet supported"); //$NON-NLS-1$ }//from ww w. ja va 2 s.co m if (trial == null) { messagePrinter.println("INTERNAL ERROR: trial==null in collectTrialInfo"); //$NON-NLS-1$ // We shouldn't have got here ! return; } Closure<TrialLoadResult> onFinish = new Closure<TrialLoadResult>() { @Override public void execute(TrialLoadResult lr) { handleTrialDataLoadResult(REFRESH_TRIAL_INFO, lr); } }; collectTrialInfoAfterClientCheck(REFRESH_TRIAL_INFO, trial, onFinish); }
From source file:gov.nih.nci.cabig.caaers.rules.business.service.EvaluationServiceImpl.java
/** * Evaluate the mandatoryness of a specific report, the {@link gov.nih.nci.cabig.caaers.domain.report.ReportMandatoryField} will be populated in the Report. * @param aeReport/*from ww w. j av a2 s .c om*/ * @param report */ public void evaluateMandatoryness(final ExpeditedAdverseEventReport aeReport, final Report report) { final ReportDefinition rd = report.getReportDefinition(); //clear the mandatory fields in report final List<ReportMandatoryField> mfList = new ArrayList<ReportMandatoryField>(); report.setMandatoryFields(mfList); if (log.isDebugEnabled()) log.debug("Static Mandatory field evaluation"); //evaluation of static field rules CollectionUtils.forAllDo(rd.getAllNonRuleBasedMandatoryFields(), new Closure<ReportMandatoryFieldDefinition>() { public void execute(ReportMandatoryFieldDefinition mfd) { ReportMandatoryField mf = new ReportMandatoryField(mfd.getFieldPath(), Mandatory.NA); //update the mandatory flag if (mfd.getMandatory().equals(RequirednessIndicator.OPTIONAL)) mf.setMandatory(Mandatory.OPTIONAL); if (mfd.getMandatory().equals(RequirednessIndicator.MANDATORY)) mf.setMandatory(Mandatory.MANDATORY); if (log.isDebugEnabled()) log.debug(mfd.getFieldPath() + " -->" + mf.getMandatory().getName()); mfList.add(mf); } }); final List<Object> baseInputObjects = new ArrayList<Object>(); baseInputObjects.add(aeReport); baseInputObjects.add(rd); if (aeReport.getStudy() != null) baseInputObjects.add(aeReport.getStudy()); if (aeReport.getTreatmentInformation() != null) baseInputObjects.add(aeReport.getTreatmentInformation()); //non self referenced rules final List<Object> inputObjects = new ArrayList(baseInputObjects); inputObjects.addAll(aeReport.getActiveAdverseEvents()); final HashMap<String, Mandatory> rulesDecisionCache = new HashMap<String, Mandatory>(); if (log.isDebugEnabled()) log.debug("Non Self referenced rule evaluation"); final String fieldRulesBindURL = adverseEventEvaluationService.fetchBindURI(RuleType.FIELD_LEVEL_RULES, null, null, null); if (StringUtils.isEmpty(fieldRulesBindURL)) { log.warn("No active field level rules found, so ignoring rule based mandatoryness evaluation"); } CollectionUtils.forAllDo(rd.getNonSelfReferencedRuleBasedMandatoryFields(), new Closure<ReportMandatoryFieldDefinition>() { public void execute(ReportMandatoryFieldDefinition mfd) { String ruleName = mfd.getRuleName(); String path = mfd.getFieldPath(); Mandatory m = rulesDecisionCache.get(ruleName); if (StringUtils.isEmpty(fieldRulesBindURL)) { log.info(mfd.getFieldPath() + " marking it as optional, as there is no field rules found"); m = Mandatory.OPTIONAL; } if (m == null) { String decision = adverseEventEvaluationService .evaluateFieldLevelRules(fieldRulesBindURL, ruleName, inputObjects); if (log.isDebugEnabled()) log.debug("rules decision : " + decision); m = translateRulesMandatorynessResult(decision); rulesDecisionCache.put(ruleName, m); if (log.isDebugEnabled()) log.debug("caching --> " + m.getName()); } if (log.isDebugEnabled()) log.debug(mfd.getFieldPath() + " -->" + m.getName()); mfList.add(new ReportMandatoryField(path, m)); } }); //self referenced rules if (log.isDebugEnabled()) log.debug("Self referenced rule evaluation"); CollectionUtils.forAllDo(rd.getSelfReferencedRuleBasedMandatoryFields(), new Closure<ReportMandatoryFieldDefinition>() { public void execute(ReportMandatoryFieldDefinition mfd) { Map<String, Object> map = CaaersRuleUtil.multiplexAndEvaluate(aeReport, mfd.getFieldPath()); for (String path : map.keySet()) { List<Object> inputObjects = new ArrayList(baseInputObjects); Object o = map.get(path); if (o == null) continue; if (o instanceof Collection) { inputObjects.addAll((Collection) o); } else { inputObjects.add(o); } String decision = null; if (StringUtils.isEmpty(fieldRulesBindURL)) { log.info(mfd.getFieldPath() + " marking it as optional, as there is no field rules found"); } else { decision = adverseEventEvaluationService.evaluateFieldLevelRules(fieldRulesBindURL, mfd.getRuleName(), inputObjects); } if (log.isDebugEnabled()) log.debug("rules decision : " + decision); Mandatory m = translateRulesMandatorynessResult(decision); if (log.isDebugEnabled()) log.debug(mfd.getFieldPath() + " -->" + m.getName()); mfList.add(new ReportMandatoryField(path, m)); } } }); }