@Override
 public void postMap(
     OWLIndividual bpInstance,
     BioPAXFactory bpFactor,
     XMLFileAdaptor reactomeAdaptor,
     Map<OWLIndividual, GKInstance> bpToRInstanceMap)
     throws Exception {
   // Sort hasComponent or hasEvent attributes based on preceding/following.
   GKInstance pathway = (GKInstance) bpToRInstanceMap.get(bpInstance);
   SchemaAttribute attribute = null;
   if (pathway.getSchemClass().isValidAttribute(ReactomeJavaConstants.hasComponent))
     attribute = pathway.getSchemClass().getAttribute(ReactomeJavaConstants.hasComponent);
   else if (pathway.getSchemClass().isValidAttribute(ReactomeJavaConstants.hasEvent))
     attribute = pathway.getSchemClass().getAttribute(ReactomeJavaConstants.hasEvent);
   if (attribute == null) return;
   List originalValues = pathway.getAttributeValuesList(attribute);
   if (originalValues == null || originalValues.size() < 2) return; // No need to order
   List copy = new ArrayList(originalValues);
   for (Iterator it = copy.iterator(); it.hasNext(); ) {
     GKInstance inst = (GKInstance) it.next();
     int index = originalValues.indexOf(inst);
     List preceded = inst.getAttributeValuesList(ReactomeJavaConstants.precedingEvent);
     if (preceded == null || preceded.size() == 0) continue;
     for (Iterator it1 = preceded.iterator(); it1.hasNext(); ) {
       GKInstance tmp = (GKInstance) it1.next();
       int tmpIndex = originalValues.indexOf(tmp);
       if (tmpIndex > index) {
         originalValues.remove(tmpIndex);
         originalValues.add(index, tmp);
         index++; // Move one step
       }
     }
   }
 }
 /**
  * Overlay a single disease reaction onto a normal reaction.
  *
  * @param normalReaction
  * @param diseaseReaction
  * @param overlaidObjects
  */
 private void overlayDiseaseReaction(HyperEdge normalReaction, GKInstance diseaseReaction)
     throws Exception {
   // Make a copy of the HyperEdge for future process that is related to Vertex and JSON generation
   HyperEdge reactionCopy = normalReaction.shallowCopy();
   reactionCopy.setReactomeId(diseaseReaction.getDBID());
   reactionCopy.setDisplayName(diseaseReaction.getDisplayName());
   reactionCopy.setLineColor(DefaultRenderConstants.DEFAULT_DISEASE_BACKGROUND);
   displayedObject.addComponent(reactionCopy);
   overlaidObjects.add(reactionCopy);
   // Want to handle inputs, outputs and catalysts since regulators can
   // be ignored
   List<Node> nodes = new ArrayList<Node>();
   nodes.addAll(normalReaction.getInputNodes());
   nodes.addAll(normalReaction.getOutputNodes());
   nodes.addAll(normalReaction.getHelperNodes());
   // List objects not listed in the disease reaction as crossed objects
   Set<GKInstance> participants = InstanceUtilities.getReactionParticipants(diseaseReaction);
   Set<Long> diseaseIds = new HashSet<Long>();
   for (GKInstance participant : participants) {
     diseaseIds.add(participant.getDBID());
     if (participant.getSchemClass().isValidAttribute(ReactomeJavaConstants.hasMember)) {
       List<GKInstance> list = participant.getAttributeValuesList(ReactomeJavaConstants.hasMember);
       if (list != null && list.size() > 0) {
         for (GKInstance inst : list) diseaseIds.add(inst.getDBID());
       }
     }
     if (participant.getSchemClass().isValidAttribute(ReactomeJavaConstants.hasCandidate)) {
       List<GKInstance> list =
           participant.getAttributeValuesList(ReactomeJavaConstants.hasCandidate);
       if (list != null && list.size() > 0) {
         for (GKInstance inst : list) diseaseIds.add(inst.getDBID());
       }
     }
   }
   Set<GKInstance> lofInstances = new HashSet<GKInstance>();
   Map<Node, GKInstance> normalToDiseaseEntity =
       mapMutatedToNormalNodes(diseaseReaction, normalReaction, nodes, lofInstances);
   for (Node node : nodes) {
     if (!diseaseIds.contains(node.getReactomeId())) {
       // Check if it should be mapped to a normal entity
       GKInstance diseaseEntity = normalToDiseaseEntity.get(node);
       if (diseaseEntity == null) crossedObjects.add(node); // Just crossed out
       else {
         Node diseaseNode =
             replaceNormalNode(node, diseaseEntity, contains(diseaseEntity, lofInstances));
         if (diseaseNode == null) continue; // Just in case
         // Re-link to diseaseNode
         ConnectInfo connectInfo = reactionCopy.getConnectInfo();
         List<?> widgets = connectInfo.getConnectWidgets();
         for (Object obj : widgets) {
           ConnectWidget widget = (ConnectWidget) obj;
           if (widget.getConnectedNode() == node) widget.replaceConnectedNode(diseaseNode);
         }
       }
     } else overlaidObjects.add(node);
   }
 }
 private void getPathwayComponents(
     OWLIndividual bpInstance,
     BioPAXFactory bpFactory,
     GKInstance rPathway,
     Map<OWLIndividual, GKInstance> bpToRInstanceMap)
     throws Exception {
   OWLProperty prop = bpFactory.getOWLProperty(BioPAXJavaConstants.PATHWAY_COMPONENTS);
   Collection bpComponents = bpInstance.getPropertyValues(prop);
   if (bpComponents == null || bpComponents.size() == 0) return;
   OWLIndividual bpComp;
   RDFSClass bpCompType;
   GKInstance rComp;
   // Used to check value
   // Try to make it work for the new schema (6/13/07 - wgm)
   SchemaAttribute hasComponentAtt = null;
   if (rPathway.getSchemClass().isValidAttribute(ReactomeJavaConstants.hasComponent))
     hasComponentAtt = rPathway.getSchemClass().getAttribute(ReactomeJavaConstants.hasComponent);
   else if (rPathway.getSchemClass().isValidAttribute(ReactomeJavaConstants.hasEvent))
     hasComponentAtt = rPathway.getSchemClass().getAttribute(ReactomeJavaConstants.hasEvent);
   if (hasComponentAtt == null) return;
   // Do a sort based on NEXT_STEP
   for (Iterator it = bpComponents.iterator(); it.hasNext(); ) {
     Object obj = it.next();
     if (!(obj instanceof OWLIndividual)) {
       System.out.println(obj + " is not an OWLIndividual object!");
       throw new IllegalStateException(
           "Object in the pathway component list is not an OWLIndividual object: " + obj);
     }
     bpComp = (OWLIndividual) obj;
     bpCompType = bpComp.getRDFType();
     if (bpCompType == bpFactory.getpathwayStepClass()) {
       // Grep the wrapped interaction or pathway instances
       prop = bpFactory.getOWLProperty(BioPAXJavaConstants.STEP_INTERACTIONS);
       Collection stepInteractions = bpComp.getPropertyValues(prop);
       if (stepInteractions == null || stepInteractions.size() == 0) continue;
       for (Iterator it1 = stepInteractions.iterator(); it1.hasNext(); ) {
         OWLIndividual stepInteraction = (OWLIndividual) it1.next();
         if (stepInteraction.getRDFType() != bpFactory.getcontrolClass()) {
           rComp = bpToRInstanceMap.get(stepInteraction);
           // Some control Individuals are listed under PATHWAY_COMPONENT. However,
           // they should not be a value in hasComponent
           if (rComp != null && hasComponentAtt.isValidValue(rComp))
             rPathway.addAttributeValue(hasComponentAtt, rComp);
         }
       }
     } else if (bpCompType != bpFactory.getcontrolClass()
         && !bpCompType.isSubclassOf(bpFactory.getcontrolClass())) {
       // Another two types should be: Interaction and Pathway. But should exclude
       // control class. Control class is attached to Reaction in Reactome
       rComp = bpToRInstanceMap.get(bpComp);
       if (rComp != null) rPathway.addAttributeValue(hasComponentAtt, rComp);
     }
   }
 }
  /** Split objects into normal and disease components */
  private void splitObjects() {
    normalIds = new HashSet<Long>();
    diseaseIds = new HashSet<Long>();
    RenderablePathway diagram = (RenderablePathway) getRenderable();
    if (pathway == null || diagram.getReactomeDiagramId() == null) return;
    try {
      GKInstance pdInst = adaptor.fetchInstance(diagram.getReactomeDiagramId());
      // Get the disease pathway instance
      List<GKInstance> pathways =
          pdInst.getAttributeValuesList(ReactomeJavaConstants.representedPathway);

      GKInstance diseasePathway = null;
      GKInstance normalPathway = null;
      GKInstance disease = (GKInstance) pathway.getAttributeValue(ReactomeJavaConstants.disease);
      if (disease == null && contains(pathway, pathways)) {
        normalPathway = pathway;
      } else {
        diseasePathway = pathway;
        // There should be a normal pathway contained by a disease pathway
        List<?> subPathways = diseasePathway.getAttributeValuesList(ReactomeJavaConstants.hasEvent);
        for (Object obj : subPathways) {
          GKInstance subPathway = (GKInstance) obj;
          disease = (GKInstance) subPathway.getAttributeValue(ReactomeJavaConstants.disease);
          if (disease == null && contains(subPathway, pathways)) {
            normalPathway = subPathway;
            break;
          }
        }
      }
      if (normalPathway != null) {
        // Get all disease related objects
        Set<GKInstance> normalEvents = InstanceUtilities.grepPathwayEventComponents(normalPathway);
        for (GKInstance inst : normalEvents) normalIds.add(inst.getDBID());
        Set<GKInstance> normalEntities = InstanceUtilities.grepPathwayParticipants(normalPathway);
        for (GKInstance inst : normalEntities) normalIds.add(inst.getDBID());
        if (diseasePathway != null) {
          Set<GKInstance> allEvents = InstanceUtilities.grepPathwayEventComponents(diseasePathway);
          allEvents.removeAll(normalEvents);
          for (GKInstance inst : allEvents) {
            diseaseIds.add(inst.getDBID());
            // Want to make sure disease pathways are connected to objects
            if (inst.getSchemClass().isa(ReactomeJavaConstants.ReactionlikeEvent)) {
              Set<GKInstance> rxtEntities = InstanceUtilities.getReactionParticipants(inst);
              for (GKInstance rxtEntity : rxtEntities) {
                diseaseIds.add(rxtEntity.getDBID());
              }
            }
          }
          //                    Set<GKInstance> allEntities =
          // InstanceUtilities.grepPathwayParticipants(diseasePathway);
          //                    allEntities.removeAll(normalEntities);
          //                    for (GKInstance inst : allEntities)
          //                        diseaseIds.add(inst.getDBID());
        }
      }
      splitComponents();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /**
  * Some of disease reactions may not be drawn in the pathway diagram (e.g. LoF or GoF reactions).
  * These reactions should be overlaid onto their normalReaction counterparts, which are encoded by
  * their normalReaction attributes.
  *
  * @param diseaseIds
  */
 private void overlayDiseaseReactions(Set<Long> diseaseIds) {
   // Get the list of all drawing objects for checking
   Map<Long, Renderable> idToObject = new HashMap<Long, Renderable>();
   List<Renderable> components = displayedObject.getComponents();
   if (components == null || components.size() == 0) return;
   for (Renderable r : components) {
     if (r.getReactomeId() == null) continue;
     idToObject.put(r.getReactomeId(), r);
   }
   try {
     normalToDiseaseNode = new HashMap<Node, Node>();
     for (Long diseaseId : diseaseIds) {
       if (idToObject.containsKey(diseaseId)) continue;
       // Have to copy the normal reactions to draw
       GKInstance inst = adaptor.fetchInstance(diseaseId);
       if (inst.getSchemClass().isa(ReactomeJavaConstants.ReactionlikeEvent)) {
         List<GKInstance> normalReactions =
             inst.getAttributeValuesList(ReactomeJavaConstants.normalReaction);
         if (normalReactions != null && normalReactions.size() > 0) {
           for (GKInstance normalRxt : normalReactions) {
             Renderable r = idToObject.get(normalRxt.getDBID());
             if (r instanceof HyperEdge) overlayDiseaseReaction((HyperEdge) r, inst);
           }
         }
       }
     }
     return;
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 @Test
 public void checkReferenceMoleculeAndClassUsage() throws Exception {
   MySQLAdaptor dba =
       new MySQLAdaptor("reactomedev.oicr.on.ca", "gk_central", "authortool", "**REMOVED**");
   //        Collection<GKInstance> c =
   // dba.fetchInstancesByClass(ReactomeJavaConstants.ReferenceGroupCount);
   //        System.out.println("Total ReferenceMolecule: " + c.size());
   Collection<GKInstance> c1 =
       dba.fetchInstancesByClass(ReactomeJavaConstants.ReferenceMoleculeClass);
   System.out.println("Total ReferenceMoleculeClass: " + c1.size());
   Set<GKInstance> all = new HashSet<GKInstance>();
   //        all.addAll(c);
   all.addAll(c1);
   System.out.println("ReferenceMolecule\tReferrers");
   for (GKInstance inst : all) {
     Collection<?> refAtts = inst.getSchemClass().getReferers();
     Set<GKInstance> allReferrers = new HashSet<GKInstance>();
     for (Iterator<?> it1 = refAtts.iterator(); it1.hasNext(); ) {
       GKSchemaAttribute att = (GKSchemaAttribute) it1.next();
       Collection<GKInstance> referrers = inst.getReferers(att);
       if (referrers != null) allReferrers.addAll(referrers);
     }
     if (allReferrers.size() > 0) {
       System.out.println(inst + "\t" + join(allReferrers));
     }
   }
 }
 @Override
 protected void reinsert(DefaultMutableTreeNode treeNode, DefaultTreeModel model) {
   DefaultMutableTreeNode parent = (DefaultMutableTreeNode) treeNode.getParent();
   model.removeNodeFromParent(treeNode);
   // Check if the old parent can still be used in case type has been changed
   GKSchemaClass parentCls = (GKSchemaClass) parent.getUserObject();
   GKInstance editingInstance = (GKInstance) treeNode.getUserObject();
   if (editingInstance.getSchemClass().isa(parentCls))
     insertInstanceNodeAlphabetically(parent, treeNode);
   else {
     // Need to insert into another node
     DefaultMutableTreeNode newParent = getClassNode(editingInstance.getSchemClass());
     insertInstanceNodeAlphabetically(newParent, treeNode);
     // Check if the old parent node should be removed
     if (parent.getChildCount() == 0) model.removeNodeFromParent(parent);
   }
 }
 @Override
 public void addInstance(GKInstance instance) {
   SchemaClass cls = instance.getSchemClass();
   if (!cls.isa(ReactomeJavaConstants.PhysicalEntity) || cls.isa(ReactomeJavaConstants.Complex))
     return; // Only display non-complex PE in this class.
   DefaultMutableTreeNode clsNode = getClassNode(cls);
   DefaultMutableTreeNode instanceNode = new DefaultMutableTreeNode(instance);
   insertInstanceNodeAlphabetically(clsNode, instanceNode);
 }
 private Set<GKInstance> getReferenceEntity(GKInstance pe) throws Exception {
   Set<GKInstance> rtn = new HashSet<GKInstance>();
   if (pe.getSchemClass().isValidAttribute(ReactomeJavaConstants.referenceEntity)) {
     GKInstance ref = (GKInstance) pe.getAttributeValue(ReactomeJavaConstants.referenceEntity);
     if (ref != null) rtn.add(ref);
     return rtn;
   }
   Set<GKInstance> contained =
       InstanceUtilities.getContainedInstances(
           pe,
           ReactomeJavaConstants.hasMember,
           ReactomeJavaConstants.hasCandidate,
           ReactomeJavaConstants.hasComponent);
   // Check member or complex subunits
   for (GKInstance tmp : contained) {
     if (tmp.getSchemClass().isValidAttribute(ReactomeJavaConstants.referenceEntity)) {
       GKInstance ref = (GKInstance) tmp.getAttributeValue(ReactomeJavaConstants.referenceEntity);
       if (ref != null) rtn.add(ref);
     }
   }
   return rtn;
 }
 private void checkLossOfFunctionNodes() {
   try {
     lofNodes = new ArrayList<Node>();
     List<Renderable> components = displayedObject.getComponents();
     if (components == null || components.size() == 0) return;
     for (Renderable r : components) {
       if (r instanceof Node || r.getReactomeId() == null) continue;
       if (!diseaseIds.contains(r.getReactomeId())) continue;
       GKInstance inst = adaptor.fetchInstance(r.getReactomeId());
       if (!inst.getSchemClass().isa(ReactomeJavaConstants.ReactionlikeEvent)
           || !inst.getSchemClass().isValidAttribute(ReactomeJavaConstants.entityFunctionalStatus))
         continue;
       List<GKInstance> efs =
           inst.getAttributeValuesList(ReactomeJavaConstants.entityFunctionalStatus);
       Set<GKInstance> lofPEs = new HashSet<GKInstance>();
       for (GKInstance ef : efs) {
         GKInstance pe = (GKInstance) ef.getAttributeValue(ReactomeJavaConstants.physicalEntity);
         if (isLOFEntity(ef)) lofPEs.add(pe);
       }
       List<Node> nodes = ((HyperEdge) r).getConnectedNodes();
       for (Node node : nodes) {
         if (node.getReactomeId() == null) continue;
         GKInstance nodeInst = adaptor.fetchInstance(node.getReactomeId());
         Set<GKInstance> nodeRefEntities = getReferenceEntity(nodeInst);
         for (GKInstance lofPE : lofPEs) {
           Set<GKInstance> lofRefEntities = getReferenceEntity(lofPE);
           lofRefEntities.retainAll(nodeRefEntities);
           if (lofRefEntities.size() > 0) {
             // A LOF node
             lofNodes.add(node);
             break;
           }
         }
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  private void showComparison() {
    // Find the instance that can be used for comparision. This instance
    // should be chosen from changedList or localHasUnexpInstance
    GKInstance instance = null;
    if (changedList != null) { // Check changedList first
      List selection = changedList.getSelection();
      if (selection.size() > 0) instance = (GKInstance) selection.get(0);
    }
    if (instance == null && localHasMoreIEList != null) {
      List selection = localHasMoreIEList.getSelection();
      if (selection.size() > 0) instance = (GKInstance) selection.get(0);
    }
    if (instance == null) return;
    final InstanceComparisonPane comparisonPane = new InstanceComparisonPane();
    // Fine tune comparison pane for making comparisons with
    // database
    comparisonPane.setSaveDialogHideUnusedButtons(true);
    comparisonPane.setSaveDialogSaveAsNewBtnFirst(false);
    comparisonPane.setSaveDialogSaveAsNewBtnTitle(
        "Create new local instance and put merge into that");
    comparisonPane.setSaveDialogReplaceFirstBtnTitle(
        "Overwrite existing instance with merge (recommended)");
    comparisonPane.setCloseAfterSaving(true);
    try {
      String clsName = instance.getSchemClass().getName();
      Long instanceId = instance.getDBID();
      final GKInstance localCopy = fileAdaptor.fetchInstance(clsName, instanceId);
      dbAdaptor.setUseCache(false);
      // final GKInstance dbCopy = dbAdaptor.fetchInstance(clsName, instanceId);
      // The class type might be changed locally or remotely. So not clsName should be used
      // to fetch database instance. Otherwise, null exception will be thrown. The same thing
      // is done also in creating synchronization result.
      final GKInstance dbCopy = dbAdaptor.fetchInstance(instanceId);
      dbAdaptor.setUseCache(true);
      comparisonPane.setInstances(localCopy, dbCopy);
      String title =
          "Comparing Instances \""
              + instance.getDisplayName()
              + "\" in the local and DB repositories";
      JDialog parentDialog = (JDialog) SwingUtilities.getAncestorOfClass(JDialog.class, centerPane);
      final JDialog dialog = new JDialog(parentDialog, title);
      // Try to update the list automatically
      dialog.addWindowListener(
          new WindowAdapter() {
            public void windowClosed(WindowEvent e) {
              handleMergeResult(localCopy, dbCopy, comparisonPane);
              // To prevent double calling. It is called again when parentDialog is closed.
              dialog.removeWindowListener(this);
            }
          });
      dialog.getContentPane().add(comparisonPane, BorderLayout.CENTER);
      dialog.setModal(true);
      dialog.setSize(800, 600);
      GKApplicationUtilities.center(dialog);
      dialog.setVisible(true);

      // Update synchronization dialog panels depending on user
      // choice.
      if (comparisonPane.getSaveMergeOption() == InstanceComparisonPane.SAVE_AS_NEW) {
        GKInstance merged = comparisonPane.getMerged();

        if (newList == null) {
          List list = new ArrayList();
          list.add(merged);
          newList = initInstanceListPane(list, "Instances created locally: " + list.size());
        } else newList.addInstance(merged);
      } else if (comparisonPane.getSaveMergeOption() == InstanceComparisonPane.OVERWRITE_FIRST) {
        dbAdaptor.setUseCache(false);
        GKInstance remoteCopy = dbAdaptor.fetchInstance(instance.getDBID());
        dbAdaptor.setUseCache(true);
        if (remoteCopy != null) {
          InstanceComparer comparer = new InstanceComparer();
          int reply = comparer.compare(instance, remoteCopy);
          if (reply == InstanceComparer.LOCAL_HAS_MORE_IE) {
            if (localHasMoreIEList == null) {
              List list = new ArrayList();
              list.add(instance);
              localHasMoreIEList =
                  initInstanceListPane(
                      list, "Local instances having unexpected InstanceEdits: " + list.size());
            } else localHasMoreIEList.addInstance(instance);
          } else if (reply == InstanceComparer.IS_IDENTICAL) {
            // Merge has made local and database copies
            // identical - don't need to check in anymore
            changedList.deleteInstance(instance);
          } else if (reply != InstanceComparer.NEW_CHANGE_IN_LOCAL) {
            // Merge has produced a conflict
            typeMap.put(mapCompareResultToString(reply), instance);
          } else
            // The user should now be allowed to commit this
            // instance, because it will now have changed.
            commitToDBAction.setEnabled(true);

          JOptionPane.showMessageDialog(
              parentDialog,
              "Merge successful, you will need to check the merged instance into the database.\n\n",
              "Merge OK",
              JOptionPane.INFORMATION_MESSAGE);
        }
      }

    } catch (Exception e1) {
      System.err.println("Synchronization.createDisplayMapPane(): " + e1);
      e1.printStackTrace();
      JOptionPane.showMessageDialog(
          this,
          "Error in comparing: " + instance.toString(),
          "Error in Comparing",
          JOptionPane.ERROR_MESSAGE);
    }
  }
 @Override
 public boolean isDisplayable(GKInstance instance) {
   if (!instance.getSchemClass().isa(ReactomeJavaConstants.PhysicalEntity)
       || instance.getSchemClass().isa(ReactomeJavaConstants.Complex)) return false;
   return true;
 }