use of org.vcell.util.document.VCDocumentInfo in project vcell by virtualcell.
the class ClientRequestManager method processComparisonResult.
public void processComparisonResult(TMLPanel comparePanel, TopLevelWindowManager requester) {
if (comparePanel == null || requester == null) {
throw new IllegalArgumentException("Invalid params: " + comparePanel + " " + requester);
}
try {
final VCDocument vcDoc = comparePanel.processComparisonResult();
if (requester instanceof DatabaseWindowManager) {
final DatabaseWindowManager dataWinManager = (DatabaseWindowManager) requester;
final VCDocumentInfo vcDocInfo = getMatchingDocumentInfo(vcDoc);
this.openDocument(vcDocInfo, dataWinManager, true);
Thread waiter = new Thread() {
public void run() {
try {
BeanUtils.setCursorThroughout((Container) dataWinManager.getComponent(), Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
while (bOpening) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
String ID = vcDocInfo.getVersion().getVersionKey().toString();
DocumentWindowManager dwm = (DocumentWindowManager) ClientRequestManager.this.getMdiManager().getWindowManager(ID);
dwm.resetDocument(vcDoc);
} finally {
BeanUtils.setCursorThroughout((Container) dataWinManager.getComponent(), Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
};
waiter.start();
} else if (requester instanceof DocumentWindowManager) {
DocumentWindowManager docWinManager = (DocumentWindowManager) requester;
docWinManager.resetDocument(vcDoc);
} else {
throw new IllegalArgumentException("Invalid TopLevelWindowManager instance: " + requester.getClass().getName());
}
System.out.println("Processing new model ..." + vcDoc.getVersion().getName());
} catch (Exception e) {
e.printStackTrace(System.out);
throw new RuntimeException(e.getMessage());
}
}
use of org.vcell.util.document.VCDocumentInfo in project vcell by virtualcell.
the class ClientRequestManager method openAfterChecking.
private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindowManager requester, final boolean inNewWindow) {
final String DOCUMENT_INFO = "documentInfo";
final String SEDML_TASK = "SedMLTask";
final String SEDML_MODEL = "SedMLModel";
final String BNG_UNIT_SYSTEM = "bngUnitSystem";
/* asynchronous and not blocking any window */
bOpening = true;
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
// may want to insert corrected VCDocumentInfo later if our import debugger corrects it (BNGL Debugger).
hashTable.put(DOCUMENT_INFO, documentInfo);
// start a thread that gets it and updates the GUI by creating a new document desktop
String taskName = null;
if (documentInfo instanceof ExternalDocInfo) {
taskName = "Importing document";
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
File file = externalDocInfo.getFile();
if (file != null && !file.getName().isEmpty() && file.getName().endsWith("bngl")) {
BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
String fileText;
String originalFileText;
try {
fileText = BeanUtils.readBytesFromFile(file, null);
originalFileText = new String(fileText);
} catch (IOException e1) {
e1.printStackTrace();
DialogUtils.showErrorDialog(requester.getComponent(), "<html>Error reading file " + file.getPath() + "</html>");
return;
}
Reader reader = externalDocInfo.getReader();
boolean bException = true;
while (bException) {
try {
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
boolean bStochastic = true;
boolean bRuleBased = true;
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("temp NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
ASTModel astModel = RbmUtils.importBnglFile(reader);
// for now, hasUnitSystem() always returns false
if (astModel.hasUnitSystem()) {
bngUnitSystem = astModel.getUnitSystem();
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing.");
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
}
astModel.jjtAccept(constructionVisitor, rbmModelContainer);
bException = false;
} catch (final Exception e) {
e.printStackTrace(System.out);
BNGLDebuggerPanel panel = new BNGLDebuggerPanel(fileText, e);
int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, "Bngl Debugger: " + file.getName());
if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
throw new UserCancelException("Canceling Import");
}
// inserting <potentially> corrected DocumentInfo
fileText = panel.getText();
externalDocInfo = new ExternalDocInfo(panel.getText());
reader = externalDocInfo.getReader();
hashTable.put(DOCUMENT_INFO, externalDocInfo);
}
}
if (!originalFileText.equals(fileText)) {
// file has been modified
String message = "Importing <b>" + file.getName() + "</b> into vCell. <br>Overwrite the file on the disk?<br>";
message = "<html>" + message + "</html>";
Object[] options = { "Overwrite and Import", "Import Only", "Cancel" };
int returnCode = JOptionPane.showOptionDialog(requester.getComponent(), message, "Bngl Debugger", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
if (returnCode == JOptionPane.YES_OPTION) {
try {
FileWriter fw = new FileWriter(file);
fw.write(fileText);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (returnCode == JOptionPane.CANCEL_OPTION || returnCode == JOptionPane.CLOSED_OPTION) {
return;
}
}
if (!(bngUnitSystem.getOrigin() == BngUnitOrigin.PARSER)) {
BNGLUnitsPanel panel = new BNGLUnitsPanel(bngUnitSystem);
int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, " Bngl Units Selector", null, false);
if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
// TODO: or do nothing and continue with default values?
return;
} else {
bngUnitSystem = panel.getUnits();
}
}
hashTable.put(BNG_UNIT_SYSTEM, bngUnitSystem);
} else if (file != null && !file.getName().isEmpty() && file.getName().toLowerCase().endsWith(".sedml")) {
try {
XMLSource xmlSource = externalDocInfo.createXMLSource();
File sedmlFile = xmlSource.getXmlFile();
SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
if (sedml == null || sedml.getModels().isEmpty()) {
return;
}
AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(), file.getName());
hashTable.put(SEDML_MODEL, sedml);
hashTable.put(SEDML_TASK, chosenTask);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("failed to read document: " + e.getMessage(), e);
}
} else if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
try {
ArchiveComponents ac = null;
ac = Libsedml.readSEDMLArchive(new FileInputStream(file));
SEDMLDocument doc = ac.getSedmlDocument();
SedML sedml = doc.getSedMLModel();
if (sedml == null) {
throw new RuntimeException("Failed importing " + file.getName());
}
if (sedml.getModels().isEmpty()) {
throw new RuntimeException("Unable to find any model in " + file.getName());
}
AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(), file.getName());
hashTable.put(SEDML_MODEL, sedml);
hashTable.put(SEDML_TASK, chosenTask);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("failed to read archive: " + e.getMessage(), e);
}
}
} else {
taskName = "Loading document '" + documentInfo.getVersion().getName() + "' from database";
}
AsynchClientTask task0 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
public void run(Hashtable<String, Object> hashTable) throws Exception {
if (!inNewWindow) {
// request was to replace the document in an existing window
getMdiManager().blockWindow(requester.getManagerID());
}
}
};
AsynchClientTask task1 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
VCDocument doc = null;
VCDocumentInfo documentInfo = (VCDocumentInfo) hashTable.get(DOCUMENT_INFO);
if (documentInfo instanceof BioModelInfo) {
BioModelInfo bmi = (BioModelInfo) documentInfo;
doc = getDocumentManager().getBioModel(bmi);
} else if (documentInfo instanceof MathModelInfo) {
MathModelInfo mmi = (MathModelInfo) documentInfo;
doc = getDocumentManager().getMathModel(mmi);
} else if (documentInfo instanceof GeometryInfo) {
GeometryInfo gmi = (GeometryInfo) documentInfo;
doc = getDocumentManager().getGeometry(gmi);
} else if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
File file = externalDocInfo.getFile();
if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
TranslationLogger transLogger = new TranslationLogger(requester);
doc = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, (SedML) hashTable.get(SEDML_MODEL), (AbstractTask) hashTable.get(SEDML_TASK));
} else if (!externalDocInfo.isXML()) {
if (hashTable.containsKey(BNG_UNIT_SYSTEM)) {
// not XML, look for BNGL etc.
// we use the BngUnitSystem already created during the 1st pass
BngUnitSystem bngUnitSystem = (BngUnitSystem) hashTable.get(BNG_UNIT_SYSTEM);
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
SimulationContext odeSimContext = bioModel.addNewSimulationContext("BioNetGen app", SimulationContext.Application.NETWORK_DETERMINISTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
appList.add(odeSimContext);
// set convention for initial conditions in generated application for seed species (concentration or count)
ruleBasedSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
odeSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
Reader reader = externalDocInfo.getReader();
ASTModel astModel = RbmUtils.importBnglFile(reader);
if (bioModel.getModel() != null && bioModel.getModel().getVcMetaData() != null) {
VCMetaData vcMetaData = bioModel.getModel().getVcMetaData();
vcMetaData.setFreeTextAnnotation(bioModel, astModel.getProlog());
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing. Extracting it from Species, Reactions, Obserbables.");
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
}
// we'll convert the kinetic parameters to BngUnitSystem inside the visit(ASTKineticsParameter...)
astModel.jjtAccept(constructionVisitor, rbmModelContainer);
// set the volume in the newly created application to BngUnitSystem.bnglModelVolume
// TODO: set the right values if we import compartments from the bngl file!
// if(!bngUnitSystem.isConcentration()) {
Expression sizeExpression = new Expression(bngUnitSystem.getVolume());
ruleBasedSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
odeSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
// }
// we remove the NFSim application if any seed species is clamped because NFSim doesn't know what to do with it
boolean bClamped = false;
for (SpeciesContextSpec scs : ruleBasedSimContext.getReactionContext().getSpeciesContextSpecs()) {
if (scs.isConstant()) {
bClamped = true;
break;
}
}
if (bClamped) {
bioModel.removeSimulationContext(ruleBasedSimContext);
}
// // TODO: DON'T delete this code
// // the code below is needed if we also want to create simulations, example for 1 rule based simulation
// // it is rule-based so it wont have to flatten, should be fast.
// MathMappingCallback callback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
// NetworkGenerationRequirements networkGenerationRequirements = null; // network generation should not be executed.
// ruleBasedSimContext.refreshMathDescription(callback,networkGenerationRequirements);
// Simulation sim = ruleBasedSimContext.addNewSimulation(SimulationOwner.DEFAULT_SIM_NAME_PREFIX,callback,networkGenerationRequirements);
doc = bioModel;
}
} else {
// is XML
try (TranslationLogger transLogger = new TranslationLogger(requester)) {
XMLSource xmlSource = externalDocInfo.createXMLSource();
org.jdom.Element rootElement = xmlSource.getXmlDoc().getRootElement();
String xmlType = rootElement.getName();
String modelXmlType = null;
if (xmlType.equals(XMLTags.VcmlRootNodeTag)) {
// For now, assuming that <vcml> element has only one child (biomodel, mathmodel or geometry).
// Will deal with multiple children of <vcml> Element when we get to model composition.
@SuppressWarnings("unchecked") List<Element> childElementList = rootElement.getChildren();
// assuming first child is the biomodel, mathmodel or geometry.
Element modelElement = childElementList.get(0);
modelXmlType = modelElement.getName();
}
if (xmlType.equals(XMLTags.BioModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.BioModelTag))) {
doc = XmlHelper.XMLToBioModel(xmlSource);
} else if (xmlType.equals(XMLTags.MathModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.MathModelTag))) {
doc = XmlHelper.XMLToMathModel(xmlSource);
} else if (xmlType.equals(XMLTags.GeometryTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.GeometryTag))) {
doc = XmlHelper.XMLToGeometry(xmlSource);
} else if (xmlType.equals(XMLTags.SbmlRootNodeTag)) {
Namespace namespace = rootElement.getNamespace(XMLTags.SBML_SPATIAL_NS_PREFIX);
boolean bIsSpatial = (namespace == null) ? false : true;
doc = XmlHelper.importSBML(transLogger, xmlSource, bIsSpatial);
} else if (xmlType.equals(XMLTags.CellmlRootNodeTag)) {
if (requester instanceof BioModelWindowManager) {
doc = XmlHelper.importBioCellML(transLogger, xmlSource);
} else {
doc = XmlHelper.importMathCellML(transLogger, xmlSource);
}
} else if (xmlType.equals(MicroscopyXMLTags.FRAPStudyTag)) {
doc = VFrapXmlHelper.VFRAPToBioModel(hashTable, xmlSource, getDocumentManager(), requester);
} else if (xmlType.equals(XMLTags.SedMLTypeTag)) {
doc = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, (SedML) hashTable.get(SEDML_MODEL), (AbstractTask) hashTable.get(SEDML_TASK));
} else {
// unknown XML format
throw new RuntimeException("unsupported XML format, first element tag is <" + rootElement.getName() + ">");
}
if (externalDocInfo.getDefaultName() != null) {
doc.setName(externalDocInfo.getDefaultName());
}
}
}
if (doc == null) {
File f = externalDocInfo.getFile();
if (f != null) {
throw new RuntimeException("Unable to determine type of file " + f.getCanonicalPath());
}
throw new ProgrammingException();
}
}
// create biopax objects using annotation
if (doc instanceof BioModel) {
BioModel bioModel = (BioModel) doc;
try {
bioModel.getVCMetaData().createBioPaxObjects(bioModel);
} catch (Exception e) {
e.printStackTrace();
}
}
requester.prepareDocumentToLoad(doc, inNewWindow);
hashTable.put("doc", doc);
}
};
AsynchClientTask task2 = new AsynchClientTask("Showing document", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
try {
Throwable exc = (Throwable) hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR);
if (exc == null) {
VCDocument doc = (VCDocument) hashTable.get("doc");
DocumentWindowManager windowManager = null;
if (inNewWindow) {
windowManager = createDocumentWindowManager(doc);
// request was to create a new top-level window with this doc
getMdiManager().createNewDocumentWindow(windowManager);
// if (windowManager instanceof BioModelWindowManager) {
// ((BioModelWindowManager)windowManager).preloadApps();
// }
} else {
// request was to replace the document in an existing window
windowManager = (DocumentWindowManager) requester;
getMdiManager().setCanonicalTitle(requester.getManagerID());
windowManager.resetDocument(doc);
}
hashTable.put(WIN_MGR_KEY, windowManager);
}
} finally {
if (!inNewWindow) {
getMdiManager().unBlockWindow(requester.getManagerID());
}
bOpening = false;
}
}
};
AsynchClientTask task3 = new AsynchClientTask("Special Layout", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
// TODO Auto-generated method stub
if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
if (externalDocInfo.isBioModelsNet()) {
DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
if (windowManager instanceof BioModelWindowManager) {
((BioModelWindowManager) windowManager).specialLayout();
}
}
}
}
};
AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] { task0, task1, task2, task3, task4 }, false);
}
use of org.vcell.util.document.VCDocumentInfo in project vcell by virtualcell.
the class DatabaseWindowManager method openLatest.
/**
* Insert the method's description here.
* Creation date: (6/1/2004 9:49:06 PM)
*/
public void openLatest() {
VCDocumentInfo latestDocumentInfo = null;
if (getPanelSelection() != null) {
VCDocumentInfo thisDocumentInfo = getPanelSelection();
//
// Get the latest version of the documentInfo
//
VCDocumentInfo[] documentVersionsList = null;
try {
documentVersionsList = getDocumentVersionDates(thisDocumentInfo);
} catch (DataAccessException e) {
PopupGenerator.showErrorDialog(this, "Error accessing document!");
}
//
if (documentVersionsList != null && documentVersionsList.length > 0) {
latestDocumentInfo = documentVersionsList[documentVersionsList.length - 1];
for (int i = 0; i < documentVersionsList.length; i++) {
if (documentVersionsList[i].getVersion().getDate().after(latestDocumentInfo.getVersion().getDate())) {
latestDocumentInfo = documentVersionsList[i];
}
}
if (thisDocumentInfo.getVersion().getDate().after(latestDocumentInfo.getVersion().getDate())) {
latestDocumentInfo = thisDocumentInfo;
}
} else {
latestDocumentInfo = thisDocumentInfo;
}
} else {
PopupGenerator.showErrorDialog(this, "Error Opening Latest Document : no document currently selected.");
return;
}
getRequestManager().openDocument(latestDocumentInfo, this, true);
}
use of org.vcell.util.document.VCDocumentInfo in project vcell by virtualcell.
the class DatabaseWindowManager method compareAnotherModel.
/**
* Comment
*/
public void compareAnotherModel() {
//
if (getPanelSelection() == null) {
PopupGenerator.showErrorDialog(this, "Error Comparing documents : First document not selected");
return;
}
VCDocumentInfo thisDocumentInfo = getPanelSelection();
// Choose the other documentInfo. Bring up the appropriate dbTreePanel depending on the type of thisDocumentInfo
VCDocumentInfo otherDocumentInfo = null;
try {
otherDocumentInfo = selectDocument(thisDocumentInfo.getVCDocumentType(), this);
} catch (Exception e) {
if (!(e instanceof UserCancelException)) {
e.printStackTrace();
DialogUtils.showErrorDialog(this.getComponent(), "Error Comparing documents: " + e.getMessage());
}
return;
}
if (otherDocumentInfo == null) {
// PopupGenerator.showErrorDialog(this, "Error Comparing documents : Second document is null ");
return;
}
// Check if both document types are of the same kind. If not, throw an error.
if (((thisDocumentInfo instanceof BioModelInfo) && !(otherDocumentInfo instanceof BioModelInfo)) || ((thisDocumentInfo instanceof MathModelInfo) && !(otherDocumentInfo instanceof MathModelInfo)) || ((thisDocumentInfo instanceof GeometryInfo) && !(otherDocumentInfo instanceof GeometryInfo))) {
PopupGenerator.showErrorDialog(this, "Error Comparing documents : The two documents are not of the same type!");
return;
}
// Now that we have both the document versions to be compared, do the comparison and display the result
compareWithOther(otherDocumentInfo, thisDocumentInfo);
}
use of org.vcell.util.document.VCDocumentInfo in project vcell by virtualcell.
the class TestingFrameworkWindowManager method queryTCritCrossRef.
@SuppressWarnings("serial")
public void queryTCritCrossRef(final TestSuiteInfoNew tsin, final TestCriteriaNew tcrit, final String varName) {
try {
QueryTestCriteriaCrossRefOP queryTestCriteriaCrossRefOP = new QueryTestCriteriaCrossRefOP(tsin.getTSKey(), tcrit.getTCritKey(), varName);
TestCriteriaCrossRefOPResults testCriteriaCrossRefOPResults = (TestCriteriaCrossRefOPResults) getRequestManager().getDocumentManager().doTestSuiteOP(queryTestCriteriaCrossRefOP);
final Vector<TestCriteriaCrossRefOPResults.CrossRefData> xrefDataV = testCriteriaCrossRefOPResults.getCrossRefData();
final TestSuiteInfoNew[] testSuiteInfos = getRequestManager().getDocumentManager().getTestSuiteInfos();
Vector<TestSuiteInfoNew> missingTestSuites = new Vector<TestSuiteInfoNew>();
for (int i = 0; i < testSuiteInfos.length; i++) {
boolean bFound = false;
for (int j = 0; j < xrefDataV.size(); j++) {
if (xrefDataV.elementAt(j).tsVersion.equals(testSuiteInfos[i].getTSID())) {
bFound = true;
break;
}
}
if (!bFound) {
missingTestSuites.add(testSuiteInfos[i]);
}
}
TestCriteriaCrossRefOPResults.CrossRefData xrefDataSource = null;
for (int i = 0; i < xrefDataV.size(); i++) {
if (xrefDataV.elementAt(i).tcritKey.equals(tcrit.getTCritKey())) {
xrefDataSource = xrefDataV.elementAt(i);
break;
}
}
if (xrefDataSource == null) {
throw new RuntimeException("Couldn't find source Test Criteria in query results.");
}
final int numColumns = 8;
final int XREFDATA_ALLOWANCE = 1;
final int TSKEY_ALLOWANCE = 1;
final int XREFDATA_OFFSET = numColumns;
final int TSDATE_OFFSET = 1;
final int VARNAME_OFFSET = 3;
final int TSKEYMISSING_OFFSET = numColumns + 1;
final String[] colNames = new String[numColumns];
final Object[][] sourceRows = new Object[xrefDataV.size() + missingTestSuites.size()][numColumns + XREFDATA_ALLOWANCE + TSKEY_ALLOWANCE];
String sourceTestSuite = null;
colNames[0] = "tsVersion";
colNames[1] = "tsDate";
colNames[2] = "tsBaseVersion";
colNames[3] = "varName";
colNames[4] = "RelErorr";
colNames[5] = "limitRelErorr";
colNames[6] = "limitAbsErorr";
colNames[7] = "AbsErorr";
for (int i = 0; i < xrefDataV.size(); i++) {
sourceRows[i][colNames.length] = xrefDataV.elementAt(i);
if (xrefDataV.elementAt(i).tcritKey.equals(queryTestCriteriaCrossRefOP.getTestCriterium())) {
sourceTestSuite = xrefDataV.elementAt(i).tsVersion;
}
sourceRows[i][0] = xrefDataV.elementAt(i).tsVersion;
sourceRows[i][2] = (xrefDataV.elementAt(i).tsRefVersion == null ? (xrefDataV.elementAt(i).regressionModelID == null ? /* && xrefDataV.elementAt(i).regressionMMref==null*/
"" : "Ref Model exist BUT outside of TestSuites") : xrefDataV.elementAt(i).tsRefVersion);
sourceRows[i][6] = xrefDataV.elementAt(i).maxAbsErorr;
sourceRows[i][5] = xrefDataV.elementAt(i).maxRelErorr;
if (xrefDataV.elementAt(i).varName != null) {
sourceRows[i][VARNAME_OFFSET] = xrefDataV.elementAt(i).varName;
sourceRows[i][4] = xrefDataV.elementAt(i).varCompSummary.getRelativeError();
sourceRows[i][7] = xrefDataV.elementAt(i).varCompSummary.getAbsoluteError();
} else {
sourceRows[i][VARNAME_OFFSET] = "-No Report-";
// "No Report";
sourceRows[i][4] = null;
// "No Report";
sourceRows[i][7] = null;
}
for (int j = 0; j < testSuiteInfos.length; j++) {
if (xrefDataV.elementAt(i).tsVersion.equals(testSuiteInfos[j].getTSID())) {
sourceRows[i][1] = testSuiteInfos[j].getTSDate();
break;
}
}
}
for (int i = xrefDataV.size(); i < sourceRows.length; i++) {
sourceRows[i][0] = missingTestSuites.elementAt(i - xrefDataV.size()).getTSID();
sourceRows[i][TSDATE_OFFSET] = missingTestSuites.elementAt(i - xrefDataV.size()).getTSDate();
sourceRows[i][TSKEYMISSING_OFFSET] = missingTestSuites.elementAt(i - xrefDataV.size()).getTSKey();
}
// Arrays.sort(rows,
// new Comparator<Object[]>(){
// public int compare(Object[] o1, Object[] o2) {
// return ((String)o1[0]).compareToIgnoreCase((String)o2[0]);
// // if(o1[0].equals(o2[0])){
// // return o1[3].compareToIgnoreCase(o2[3]);
// // }
// // return o1[0].compareToIgnoreCase(o2[0]);
// }
// }
// );
final VCellSortTableModel<Object[]> tableModel = new VCellSortTableModel<Object[]>(colNames) {
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == TSDATE_OFFSET) {
return Date.class;
} else if (columnIndex >= 4 && columnIndex <= 7) {
return Double.class;
}
return String.class;
}
public boolean isCellEditable(int row, int column) {
return false;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return getValueAt(rowIndex)[columnIndex];
}
public Comparator<Object[]> getComparator(final int col, final boolean ascending) {
return new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
if (o1[col] == null && o2[col] == null) {
return 0;
}
// if(ascending){
if (o1[col] == null) {
return 1;
}
if (o2[col] == null) {
return -1;
}
// }
if (getColumnClass(col).equals(String.class)) {
if (ascending) {
return ((String) o1[col]).compareToIgnoreCase(((String) o2[col]));
} else {
return ((String) o2[col]).compareToIgnoreCase(((String) o1[col]));
}
} else if (getColumnClass(col).equals(Date.class)) {
if (ascending) {
return ((Date) o1[col]).compareTo(((Date) o2[col]));
}
return ((Date) o2[col]).compareTo(((Date) o1[col]));
} else if (getColumnClass(col).equals(Double.class)) {
if (ascending) {
return ((Double) o1[col]).compareTo(((Double) o2[col]));
}
return ((Double) o2[col]).compareTo(((Double) o1[col]));
}
throw new RuntimeException("TestSuite XRef Query unexpecte column class " + getColumnClass(col).getName());
}
};
}
};
tableModel.setData(Arrays.asList(sourceRows));
// Create table
final JSortTable table = new JSortTable();
table.setModel(tableModel);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
final JScrollPane scrollPaneContentPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(500, 250));
table.getColumnModel().getColumn(TSDATE_OFFSET).setCellRenderer(new DefaultTableCellRenderer() {
// DateFormat formatter = DateFormat.getDateTimeInstance();
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
return super.getTableCellRendererComponent(table, (value == null ? null : ((Date) value).toString()), /*formatter.format((Date)value)*/
isSelected, hasFocus, row, column);
}
});
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer() {
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
return super.getTableCellRendererComponent(table, (value == null ? null : ((Double) value).toString()), /*formatter.format((Date)value)*/
isSelected, hasFocus, row, column);
}
};
table.getColumnModel().getColumn(4).setCellRenderer(dtcr);
table.getColumnModel().getColumn(5).setCellRenderer(dtcr);
table.getColumnModel().getColumn(6).setCellRenderer(dtcr);
table.getColumnModel().getColumn(7).setCellRenderer(dtcr);
// table.getColumnModel().getColumn(4).setCellRenderer(
// new DefaultTableCellRenderer(){
// public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
// return super.getTableCellRendererComponent(table,(value == null?null:((Double)value).toString())/*formatter.format((Date)value)*/, isSelected, hasFocus, row, column);
// }
// }
// );
// table.getTableHeader().setReorderingAllowed(false);
// Popup Menu
final TestCriteriaCrossRefOPResults.CrossRefData xrefDataSourceFinal = xrefDataSource;
final JPopupMenu queryPopupMenu = new JPopupMenu();
final JMenuItem changeLimitsMenuItem = new JMenuItem("Change Selected Error Limits...");
final String OPEN_MODEL = "Open Model(s)";
final JMenuItem openModelMenuItem = new JMenuItem(OPEN_MODEL);
final String OPEN_REGRREFMODEL = "Open Regr Ref Model(s)";
final JMenuItem openRegrRefModelMenuItem = new JMenuItem(OPEN_REGRREFMODEL);
final String SELECT_REF_IN_TREE = "Select in Tree View";
final JMenuItem showInTreeMenuItem = new JMenuItem(SELECT_REF_IN_TREE);
final String SELECT_REGR_REF_IN_TREE = "Select RegrRef TCase in Tree View";
final JMenuItem showRegrRefInTreeMenuItem = new JMenuItem(SELECT_REGR_REF_IN_TREE);
queryPopupMenu.add(changeLimitsMenuItem);
queryPopupMenu.add(openModelMenuItem);
queryPopupMenu.add(openRegrRefModelMenuItem);
queryPopupMenu.add(showInTreeMenuItem);
queryPopupMenu.add(showRegrRefInTreeMenuItem);
ActionListener showInTreeActionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int[] selectedRows = table.getSelectedRows();
if (selectedRows == null || selectedRows.length != 1) {
PopupGenerator.showErrorDialog(TestingFrameworkWindowManager.this, "Action " + actionEvent.getActionCommand() + " accepts only single selection!");
return;
}
TestCriteriaCrossRefOPResults.CrossRefData xrefData = (TestCriteriaCrossRefOPResults.CrossRefData) tableModel.getValueAt(selectedRows[0], XREFDATA_OFFSET);
BigDecimal missingTSKey = (BigDecimal) tableModel.getValueAt(selectedRows[0], TSKEYMISSING_OFFSET);
if (actionEvent.getActionCommand().equals(SELECT_REF_IN_TREE)) {
getTestingFrameworkWindowPanel().selectInTreeView((xrefData != null ? xrefData.tsKey : missingTSKey), (xrefData != null ? xrefData.tcaseKey : null), (xrefData != null ? xrefData.tcritKey : null));
} else if (actionEvent.getActionCommand().equals(SELECT_REGR_REF_IN_TREE)) {
if (xrefData == null) {
PopupGenerator.showErrorDialog(getComponent(), "No Regression Reference info available.");
return;
}
getTestingFrameworkWindowPanel().selectInTreeView((xrefData != null ? xrefData.regressionModelTSuiteID : null), (xrefData != null ? xrefData.regressionModelTCaseID : null), (xrefData != null ? xrefData.regressionModelTCritID : null));
}
ChildWindow childWindow = TFWFinder.findChildWindowManager(getComponent()).getChildWindowFromContentPane(scrollPaneContentPane);
if (childWindow != null) {
childWindow.show();
}
}
};
showInTreeMenuItem.addActionListener(showInTreeActionListener);
showRegrRefInTreeMenuItem.addActionListener(showInTreeActionListener);
ActionListener openModelsActionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int[] selectedRows = table.getSelectedRows();
String failureS = "";
TestCriteriaCrossRefOPResults.CrossRefData xrefData = null;
int openCount = 0;
for (int i = 0; i < selectedRows.length; i++) {
try {
xrefData = (TestCriteriaCrossRefOPResults.CrossRefData) tableModel.getValueAt(selectedRows[i], XREFDATA_OFFSET);
if (xrefData != null && (actionEvent.getActionCommand().equals(OPEN_REGRREFMODEL) ? xrefData.regressionModelID != null : true)) {
openCount += 1;
VCDocumentInfo vcDocInfo = null;
if (xrefData.isBioModel) {
vcDocInfo = getRequestManager().getDocumentManager().getBioModelInfo(new KeyValue((actionEvent.getActionCommand().equals(OPEN_REGRREFMODEL) ? xrefData.regressionModelID : xrefData.modelID)));
} else {
vcDocInfo = getRequestManager().getDocumentManager().getMathModelInfo(new KeyValue((actionEvent.getActionCommand().equals(OPEN_REGRREFMODEL) ? xrefData.regressionModelID : xrefData.modelID)));
}
getRequestManager().openDocument(vcDocInfo, TestingFrameworkWindowManager.this, true);
}
} catch (Exception e) {
failureS += failureS + "key=" + xrefData.modelID + " " + e.getMessage() + "\n";
e.printStackTrace();
}
}
if (failureS.length() > 0 || openCount == 0) {
PopupGenerator.showErrorDialog(TestingFrameworkWindowManager.this, "Failed to open some models\n" + failureS + (openCount == 0 ? "Selection(s) had no model(s)" : ""));
}
ChildWindow childWindow = TFWFinder.findChildWindowManager(getComponent()).getChildWindowFromContentPane(scrollPaneContentPane);
if (childWindow != null) {
childWindow.show();
}
}
};
openModelMenuItem.addActionListener(openModelsActionListener);
openRegrRefModelMenuItem.addActionListener(openModelsActionListener);
changeLimitsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int[] selectedRows = table.getSelectedRows();
Vector<TestCriteriaCrossRefOPResults.CrossRefData> changeTCritV = new Vector<TestCriteriaCrossRefOPResults.CrossRefData>();
for (int i = 0; i < selectedRows.length; i++) {
TestCriteriaCrossRefOPResults.CrossRefData xrefData = (TestCriteriaCrossRefOPResults.CrossRefData) tableModel.getValueAt(selectedRows[i], XREFDATA_OFFSET);
if (xrefData != null) {
boolean bFound = false;
for (int j = 0; j < changeTCritV.size(); j++) {
if (changeTCritV.elementAt(j).tcritKey.equals(xrefData.tcritKey)) {
bFound = true;
break;
}
}
if (!bFound) {
changeTCritV.add(xrefData);
}
}
}
if (changeTCritV.size() > 0) {
Double relativeErrorLimit = null;
Double absoluteErrorLimit = null;
while (true) {
try {
String ret = PopupGenerator.showInputDialog(getComponent(), "Enter new TestCriteria Error Limits for '" + xrefDataSourceFinal.simName + "'. '-'(dash) to keep original value.", "RelativeErrorLimit,AbsoluteErrorLimit");
int commaPosition = ret.indexOf(',');
if (commaPosition == -1) {
throw new Exception("No comma found separating RelativeErrorLimit AbsoluteErrorLimit");
}
if (commaPosition != ret.lastIndexOf(',')) {
throw new Exception("Only 1 comma allowed separating RelativeErrorLimit and AbsoluteErrorLimit");
}
final String KEEP_ORIGINAL_VALUE = "-";
String relativeErrorS = ret.substring(0, commaPosition);
String absoluteErrorS = ret.substring(commaPosition + 1, ret.length());
if (!relativeErrorS.equals(KEEP_ORIGINAL_VALUE)) {
relativeErrorLimit = Double.parseDouble(relativeErrorS);
}
if (!absoluteErrorS.equals(KEEP_ORIGINAL_VALUE)) {
absoluteErrorLimit = Double.parseDouble(absoluteErrorS);
}
if ((relativeErrorLimit != null && relativeErrorLimit <= 0) || (absoluteErrorLimit != null && absoluteErrorLimit <= 0)) {
throw new Exception("Error limits must be greater than 0");
}
break;
} catch (UserCancelException e) {
ChildWindow childWindow = TFWFinder.findChildWindowManager(getComponent()).getChildWindowFromContentPane(scrollPaneContentPane);
if (childWindow != null) {
childWindow.show();
}
return;
} catch (Exception e) {
PopupGenerator.showErrorDialog(TestingFrameworkWindowManager.this, "Error parsing Error Limits\n" + e.getMessage());
}
}
double[] relErrorLimitArr = new double[changeTCritV.size()];
double[] absErrorLimitArr = new double[changeTCritV.size()];
Object[][] rows = new Object[changeTCritV.size()][5];
for (int j = 0; j < changeTCritV.size(); j++) {
relErrorLimitArr[j] = (relativeErrorLimit != null ? relativeErrorLimit.doubleValue() : changeTCritV.elementAt(j).maxRelErorr);
absErrorLimitArr[j] = (absoluteErrorLimit != null ? absoluteErrorLimit.doubleValue() : changeTCritV.elementAt(j).maxAbsErorr);
rows[j][2] = new Double(relErrorLimitArr[j]);
rows[j][4] = new Double(absErrorLimitArr[j]);
rows[j][1] = new Double(changeTCritV.elementAt(j).maxRelErorr);
rows[j][3] = new Double(changeTCritV.elementAt(j).maxAbsErorr);
rows[j][0] = changeTCritV.elementAt(j).tsVersion;
}
try {
PopupGenerator.showComponentOKCancelTableList(getComponent(), "Confirm Error Limit Changes", new String[] { "TSVersion", "Orig RelErrorLimit", "New RelErrorLimit", "Orig AbsErrorLimit", "New AbsErrorLimit" }, rows, null);
} catch (UserCancelException e) {
ChildWindow childWindow = TFWFinder.findChildWindowManager(getComponent()).getChildWindowFromContentPane(scrollPaneContentPane);
if (childWindow != null) {
childWindow.show();
}
return;
}
// Get information needed to generate new TestCriteria Reports
final String YES_ANSWER = "Yes";
Hashtable<TestSuiteInfoNew, Vector<TestCriteriaCrossRefOPResults.CrossRefData>> genReportHash = null;
String genRepResult = PopupGenerator.showWarningDialog(getComponent(), "Generate Reports for changed Test Criterias?", new String[] { YES_ANSWER, "No" }, YES_ANSWER);
if (genRepResult != null && genRepResult.equals(YES_ANSWER)) {
genReportHash = new Hashtable<TestSuiteInfoNew, Vector<TestCriteriaCrossRefOPResults.CrossRefData>>();
for (int i = 0; i < changeTCritV.size(); i++) {
boolean bFound = false;
for (int j = 0; j < testSuiteInfos.length; j++) {
if (changeTCritV.elementAt(i).tsVersion.equals(testSuiteInfos[j].getTSID())) {
bFound = true;
Vector<TestCriteriaCrossRefOPResults.CrossRefData> tempV = genReportHash.get(testSuiteInfos[j]);
if (tempV == null) {
tempV = new Vector<TestCriteriaCrossRefOPResults.CrossRefData>();
genReportHash.put(testSuiteInfos[j], tempV);
}
tempV.add(changeTCritV.elementAt(i));
}
}
if (!bFound) {
PopupGenerator.showErrorDialog(TestingFrameworkWindowManager.this, "Couldn't find testsuiteinfo for testcriteria");
return;
}
}
}
BigDecimal[] changeTCritBDArr = new BigDecimal[changeTCritV.size()];
for (int i = 0; i < changeTCritV.size(); i++) {
changeTCritBDArr[i] = changeTCritV.elementAt(i).tcritKey;
}
ChangeTestCriteriaErrorLimitOP changeTestCriteriaErrorLimitOP = new ChangeTestCriteriaErrorLimitOP(changeTCritBDArr, absErrorLimitArr, relErrorLimitArr);
try {
getTestingFrameworkWindowPanel().getDocumentManager().doTestSuiteOP(changeTestCriteriaErrorLimitOP);
} catch (Exception e) {
PopupGenerator.showErrorDialog(TestingFrameworkWindowManager.this, "Failed Changing Error limits for selected " + xrefDataSourceFinal.simName + "\n" + e.getMessage());
return;
}
ChildWindow childWindow = TFWFinder.findChildWindowManager(getComponent()).getChildWindowFromContentPane(scrollPaneContentPane);
if (childWindow != null) {
childWindow.close();
}
getTestingFrameworkWindowPanel().refreshTree((TestSuiteInfoNew) null);
if (genReportHash != null) {
updateReports(genReportHash);
} else {
new Thread(new Runnable() {
public void run() {
TestingFrameworkWindowManager.this.queryTCritCrossRef(tsin, tcrit, varName);
}
}).start();
}
} else {
PopupGenerator.showErrorDialog(TestingFrameworkWindowManager.this, "No selected rows contain Test Criteria.");
}
}
});
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
checkPopup(e);
}
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
checkPopup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
checkPopup(e);
}
private void checkPopup(MouseEvent mouseEvent) {
if (mouseEvent.isPopupTrigger()) {
// Not use because popupmenu will not show at edge
// if(table.getSelectedRowCount() <= 1){
// table.getSelectionModel().setSelectionInterval(table.rowAtPoint(mouseEvent.getPoint()),table.rowAtPoint(mouseEvent.getPoint()));
// }
doPopup(mouseEvent);
} else {
queryPopupMenu.setVisible(false);
}
}
private void doPopup(MouseEvent mouseEvent) {
// queryPopupMenu.add(showInTreeMenuItem);
if (table.getSelectedRowCount() == 0) {
changeLimitsMenuItem.setEnabled(false);
openModelMenuItem.setEnabled(false);
openRegrRefModelMenuItem.setEnabled(false);
showInTreeMenuItem.setEnabled(false);
showRegrRefInTreeMenuItem.setEnabled(false);
} else {
changeLimitsMenuItem.setEnabled(true);
openModelMenuItem.setEnabled(true);
openRegrRefModelMenuItem.setEnabled(true);
showInTreeMenuItem.setEnabled(true);
if (table.getSelectedRowCount() == 1) {
TestCriteriaCrossRefOPResults.CrossRefData xrefData = (TestCriteriaCrossRefOPResults.CrossRefData) tableModel.getValueAt(table.getSelectedRow(), numColumns);
showRegrRefInTreeMenuItem.setEnabled(xrefData != null && xrefData.regressionModelID != null && xrefData.tsRefVersion != null);
}
}
queryPopupMenu.show(mouseEvent.getComponent(), mouseEvent.getPoint().x, mouseEvent.getPoint().y);
}
});
String title = (xrefDataSource.isBioModel ? "BM" : "MM") + " " + xrefDataSource.tcSolutionType + " (" + sourceTestSuite + ") " + " \"" + (xrefDataSource.isBioModel ? xrefDataSource.bmName : xrefDataSource.mmName) + "\" :: " + (xrefDataSource.isBioModel ? "app=\"" + xrefDataSource.bmAppName + "\" :: sim=\"" + xrefDataSource.simName + "\"" : "sim=\"" + xrefDataSource.simName + "\"");
ChildWindow childWindow = TFWFinder.findChildWindowManager(getComponent()).addChildWindow(scrollPaneContentPane, scrollPaneContentPane, title);
// childWindow.setSize(600,400);
childWindow.setIsCenteredOnParent();
childWindow.pack();
childWindow.setResizable(true);
childWindow.show();
} catch (DataAccessException e) {
e.printStackTrace();
PopupGenerator.showErrorDialog(TestingFrameworkWindowManager.this, "Error Query TestCriteria Cross Ref:\n" + e.getMessage());
}
}
Aggregations