/**
  * Called by makePathQueryForCollection
  *
  * @param webConfig the webConfig
  * @param model the object model
  * @param object the InterMineObject
  * @param field the name of the field for the collection in the InterMineObject
  * @param sr the list of classes and subclasses
  * @return a PathQuery
  */
 private static PathQuery makePathQueryForCollectionForClass(
     WebConfig webConfig, Model model, InterMineObject object, String field, List<Class<?>> sr) {
   Class<?> commonClass = CollectionUtil.findCommonSuperclass(sr);
   String typeOfCollection = TypeUtil.unqualifiedName(DynamicUtil.getSimpleClassName(commonClass));
   String startClass = TypeUtil.unqualifiedName(DynamicUtil.getSimpleClassName(object.getClass()));
   String collectionPath = startClass + "." + field;
   PathQuery pathQuery =
       getQueryWithDefaultView(typeOfCollection, model, webConfig, collectionPath);
   pathQuery.addConstraint(Constraints.eq(startClass + ".id", object.getId().toString()));
   return pathQuery;
 }
  /**
   * Create a PathQuery to get results for a collection of items from an InterMineObject
   *
   * @param webConfig the WebConfig
   * @param os the production ObjectStore
   * @param object the InterMineObject
   * @param referencedClassName the collection type
   * @param field the name of the field for the collection in the InterMineObject
   * @return a PathQuery
   */
  public static PathQuery makePathQueryForCollection(
      WebConfig webConfig,
      ObjectStore os,
      InterMineObject object,
      String referencedClassName,
      String field) {

    String className = TypeUtil.unqualifiedName(DynamicUtil.getSimpleClassName(object.getClass()));
    Path path;
    try {
      path = new Path(os.getModel(), className + "." + field);
    } catch (PathException e) {
      throw new IllegalArgumentException(
          "Could not build path for \"" + className + "." + field + "\".");
    }
    List<Class<?>> types = new ArrayList<Class<?>>();
    if (path.endIsCollection()) {
      CollectionDescriptor end = (CollectionDescriptor) path.getEndFieldDescriptor();
      // Only look for types if the refClass exactly matches the path type.
      if (end.getReferencedClassName().equals(referencedClassName)) {
        types = queryForTypesInCollection(object, field, os);
      }
      if (types.isEmpty()) {
        // the collection was empty, but still generate a query with the collection type
        types.add(os.getModel().getClassDescriptorByName(referencedClassName).getType());
      }
    } else if (path.endIsReference()) {
      types.add(path.getLastClassDescriptor().getType());
    }
    return makePathQueryForCollectionForClass(webConfig, os.getModel(), object, field, types);
  }
Пример #3
0
  // Test with a PathQuery and some dummy results, call method with a made up row,
  // create expected ResultElements.  Doesn't need too much testing as Path.resolve() is tested.
  public void testTranslateRow() throws Exception {
    PathQuery pq = new PathQuery(model);
    pq.addViews("Department.name", "Department.company.name", "Department.manager.name");
    Map<String, QuerySelectable> pathToQueryNode = new HashMap();
    Query query = MainHelper.makeQuery(pq, new HashMap(), pathToQueryNode, null, null);
    Results results = osd.execute(query);
    WebResults webResults = new WebResults(im, pq, results, pathToQueryNode, classKeys);
    List row1 = webResults.getResultElements(0);

    Department dept1 = new Department();
    dept1.setId(new Integer(4));
    dept1.setName("Department1");
    ResultElement res1 = new ResultElement(dept1, new Path(model, "Department.name"), false);

    Company c1 =
        (Company) DynamicUtil.instantiateObject("org.intermine.model.testmodel.Company", null);
    c1.setId(new Integer(1));
    c1.setName("Company1");
    ResultElement res2 = new ResultElement(c1, new Path(model, "Department.company.name"), false);

    Manager m1 = new Manager();
    m1.setId(new Integer(1));
    m1.setSeniority(new Integer(100));
    m1.setName("Manager1");
    ResultElement res3 = new ResultElement(m1, new Path(model, "Department.manager.name"), false);

    ResultsRow expected = new ResultsRow();
    expected.add(new MultiRowFirstValue(res1, 1));
    expected.add(new MultiRowFirstValue(res2, 1));
    expected.add(new MultiRowFirstValue(res3, 1));
    assertEquals(new MultiRow(Collections.singletonList(expected)), row1);
  }
Пример #4
0
 @BeforeClass
 public static void loadData() {
   made = 0;
   try {
     osw = ObjectStoreWriterFactory.getObjectStoreWriter("osw.unittest");
     Model m = osw.getModel();
     osw.beginTransaction();
     int scale = MAX_SCALE;
     try {
       for (int j = 20; j <= 90; j += 10) {
         int count = generator.nextInt(scale) + MIN_BIN; // 10 * (j % 100);
         expected.put(j, Long.valueOf(count));
         for (int i = 0; i < count; i++) {
           Types thing = DynamicUtil.createObject(Types.class);
           thing.setIntType(generator.nextInt(10) + j);
           thing.setDoubleType((generator.nextGaussian() * 5d) + 30d);
           thing.setName("histothing" + String.format("%06d", made++));
           osw.store(thing);
         }
       }
       osw.commitTransaction();
     } catch (ObjectStoreException e) {
       osw.abortTransaction();
       throw e;
     }
   } catch (ObjectStoreException e) {
     LOG.error(e);
   }
   showHistogram("Expected", expected);
   System.out.printf("Made %d things\n", made);
 }
Пример #5
0
  /** {@inheritDoc} */
  @Override
  public ActionForward execute(
      @SuppressWarnings("unused") ActionMapping mapping,
      @SuppressWarnings("unused") ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);
    ObjectStore os = im.getObjectStore();
    WebConfig webConfig = SessionMethods.getWebConfig(request);
    Integer objectId = new Integer(request.getParameter("object"));
    String fieldName = request.getParameter("field");
    String fileType = request.getParameter("type");
    InterMineObject object = os.getObjectById(objectId);

    FieldExporter fieldExporter = null;

    Set classes = DynamicUtil.decomposeClass(object.getClass());

    Iterator classIter = classes.iterator();

    while (classIter.hasNext()) {
      Class c = (Class) classIter.next();

      Type thisTypeConfig = webConfig.getTypes().get(c.getName());

      FieldConfig fc = thisTypeConfig.getFieldConfigMap().get(fieldName);

      if (fc != null) {
        String fieldExporterClassName = fc.getFieldExporter();
        if (fieldExporterClassName != null) {
          fieldExporter = (FieldExporter) Class.forName(fieldExporterClassName).newInstance();
          break;
        }
      }
    }

    if (fieldExporter == null) {
      Object fieldValue = object.getFieldValue(fieldName);
      if (fileType == null || fileType.length() == 0) {
        response.setContentType("text/plain; charset=UTF-8");
        response.setHeader("Content-Disposition ", "inline; filename=" + fieldName + ".txt");
      } else {
        response.setContentType("text/" + fileType);
        response.setHeader(
            "Content-Disposition ", "inline; filename=" + fieldName + "." + fileType);
      }
      PrintStream out = new PrintStream(response.getOutputStream());
      if (fieldValue instanceof ClobAccess) {
        ((ClobAccess) fieldValue).drainToPrintStream(out);
      } else {
        out.print(fieldValue);
      }
      out.flush();
    } else {
      fieldExporter.exportField(object, fieldName, os, response);
    }
    return null;
  }
Пример #6
0
  /**
   * Save a single object to an existing bag.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @return an ActionForward object defining where control goes next
   */
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
    int id = Integer.parseInt(request.getParameter("object"));
    HttpSession session = request.getSession();

    final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession());

    Profile profile = SessionMethods.getProfile(session);
    String bagName = request.getParameter("bag");

    InterMineBag existingBag = profile.getSavedBags().get(bagName);
    if (existingBag != null) {
      // TODO add a warning when object already in bag ??
      try {
        InterMineObject o = im.getObjectStore().getObjectById(id);
        existingBag.addIdToBag(id, DynamicUtil.getFriendlyName(o.getClass()));
        recordMessage(new ActionMessage("bag.addedToBag", existingBag.getName()), request);
      } catch (IncompatibleTypesException e) {
        recordError(new ActionMessage("bag.typesDontMatch"), request);
      } catch (ObjectStoreException e) {
        recordError(new ActionMessage("bag.error"), request, e);
      }
    } else {
      recordError(new ActionMessage("bag.noSuchBag"), request);
    }
    return mapping.findForward("report");
  }
  private void doMatches(Map<String, Object> ret, BagQueryResult bqr) {

    for (Entry<Integer, List> pair : bqr.getMatches().entrySet()) {
      Map<String, Object> resultItem;
      InterMineObject imo;
      try {
        imo = im.getObjectStore().getObjectById(pair.getKey());
      } catch (ObjectStoreException e) {
        throw new IllegalStateException("Could not retrieve object reported as match", e);
      }
      String idKey = String.valueOf(imo.getId());
      if (ret.containsKey(idKey)) {
        resultItem = (Map<String, Object>) ret.get(idKey);
      } else {
        resultItem = new HashMap<String, Object>();
        resultItem.put("identifiers", new HashMap<String, Object>());
      }
      if (!resultItem.containsKey("summary")) {
        resultItem.put("summary", getObjectDetails(imo));
      }
      Map<String, Object> identifiers = (Map<String, Object>) resultItem.get("identifiers");
      for (Object o : pair.getValue()) {
        String ident = (String) o;
        if (!identifiers.containsKey(ident)) {
          identifiers.put(ident, new HashSet<String>());
        }
        Set<String> categories = (Set<String>) identifiers.get(ident);
        categories.add("MATCH");
      }
      String className = DynamicUtil.getSimpleClassName(imo.getClass());
      resultItem.put("type", className.replaceAll("^.*\\.", ""));
      ret.put(idKey, resultItem);
    }
  }
 private Chromosome getChromosome() {
   if (chromosome == null) {
     chromosome = (Chromosome) DynamicUtil.createObject(Collections.singleton(Chromosome.class));
     chromosome.setPrimaryIdentifier("X");
     chromosome.setLength(new Integer(10000));
     chromosome.setId(new Integer(101));
   }
   return chromosome;
 }
Пример #9
0
 public void testWriteInterMineObject() throws Exception {
   InterMineObject o =
       (InterMineObject) DynamicUtil.createObject(Collections.singleton(InterMineObject.class));
   try {
     writer.store(o);
   } finally {
     writer.delete(o);
   }
 }
Пример #10
0
 public void testWriteCloneable() throws Exception {
   InterMineObject o =
       (InterMineObject)
           DynamicUtil.createObject(
               new HashSet(Arrays.asList(new Class[] {Employee.class, Cloneable.class})));
   try {
     writer.store(o);
     o = writer.getObjectById(o.getId(), Employee.class);
     if (!(o instanceof Cloneable)) {
       fail("Expected a Cloneable back");
     }
   } finally {
     writer.delete(o);
   }
 }
 private Location createLocation(
     BioEntity object,
     BioEntity subject,
     String strand,
     int start,
     int end,
     Class<?> locationClass) {
   Location loc = (Location) DynamicUtil.createObject(Collections.singleton(locationClass));
   loc.setLocatedOn(object);
   loc.setFeature(subject);
   loc.setStrand(strand);
   loc.setStart(new Integer(start));
   loc.setEnd(new Integer(end));
   loc.setStrand(strand);
   return loc;
 }
  private void doDuplicates(final Map<String, Object> ret, BagQueryResult bqr, String key) {
    Map<String, Map<String, List>> issues = bqr.getIssues().get(key);
    if (issues == null) {
      return;
    }
    for (Map<String, List> issueSet : issues.values()) {
      for (Entry<String, List> identToObjects : issueSet.entrySet()) {
        String ident = identToObjects.getKey();
        for (Object o : identToObjects.getValue()) {
          InterMineObject imo;
          Map<String, Object> resultItem;
          if (o instanceof Integer) {
            try {
              imo = im.getObjectStore().getObjectById((Integer) o);
            } catch (ObjectStoreException e) {
              throw new IllegalStateException("Could not retrieve object reported as match", e);
            }
          } else if (o instanceof ConvertedObjectPair) {
            imo = ((ConvertedObjectPair) o).getNewObject();
          } else {
            imo = (InterMineObject) o;
          }
          String idKey = String.valueOf(imo.getId());
          if (ret.containsKey(idKey)) {
            resultItem = (Map<String, Object>) ret.get(idKey);
          } else {
            resultItem = new HashMap<String, Object>();
            resultItem.put("identifiers", new HashMap<String, Object>());
          }
          if (!resultItem.containsKey("summary")) {
            resultItem.put("summary", getObjectDetails(imo));
          }
          Map<String, Object> identifiers = (Map<String, Object>) resultItem.get("identifiers");

          if (!identifiers.containsKey(ident)) {
            identifiers.put(ident, new HashSet<String>());
          }
          Set<String> categories = (Set<String>) identifiers.get(ident);
          categories.add(key);
          String className = DynamicUtil.getSimpleClassName(imo.getClass());
          resultItem.put("type", className.replaceAll("^.*\\.", ""));
          ret.put(idKey, resultItem);
        }
      }
    }
  }
Пример #13
0
 public void testWriteDynamicObject2() throws Exception {
   InterMineObject o =
       (InterMineObject)
           DynamicUtil.createObject(
               new HashSet(Arrays.asList(new Class[] {ImportantPerson.class, Employee.class})));
   try {
     writer.store(o);
     o = writer.getObjectById(o.getId(), Employee.class);
     if (!(o instanceof ImportantPerson)) {
       fail("Expected an ImportantPerson back");
     }
     if (!(o instanceof Employee)) {
       fail("Expected an Employee back");
     }
   } finally {
     writer.delete(o);
   }
 }
 private Map<String, Object> getObjectDetails(InterMineObject imo) {
   WebConfig webConfig = InterMineContext.getWebConfig();
   Model m = im.getModel();
   Map<String, Object> objectDetails = new HashMap<String, Object>();
   String className = DynamicUtil.getSimpleClassName(imo.getClass());
   ClassDescriptor cd = m.getClassDescriptorByName(className);
   for (FieldConfig fc : FieldConfigHelper.getClassFieldConfigs(webConfig, cd)) {
     try {
       Path p = new Path(m, cd.getUnqualifiedName() + "." + fc.getFieldExpr());
       if (p.endIsAttribute() && fc.getShowInSummary()) {
         objectDetails.put(
             p.getNoConstraintsString().replaceAll("^[^.]*\\.", ""), PathUtil.resolvePath(p, imo));
       }
     } catch (PathException e) {
       LOG.error(e);
     }
   }
   return objectDetails;
 }
  /**
   * From the columns of the PagedTable, return a List of the Paths that this exporter will use to
   * find sequences to export. The returned Paths are a subset of the prefixes of the column paths.
   * eg. if the columns are ("Gene.primaryIdentifier", "Gene.secondaryIdentifier",
   * "Gene.proteins.primaryIdentifier") return ("Gene", "Gene.proteins").
   *
   * @param pt the PagedTable
   * @return a list of Paths that have sequence
   */
  public static LinkedHashMap<Path, Integer> getExportClassPaths(PagedTable pt) {
    LinkedHashMap<Path, Integer> retPaths = new LinkedHashMap<Path, Integer>();

    List<Column> columns = pt.getColumns();

    for (int index = 0; index < columns.size(); index++) {
      Path prefix = columns.get(index).getPath().getPrefix();
      ClassDescriptor prefixCD = prefix.getLastClassDescriptor();
      Class<? extends FastPathObject> prefixClass = DynamicUtil.getSimpleClass(prefixCD.getType());
      // Chromosome is treated as a sequence feature in the model
      if (SequenceFeature.class.isAssignableFrom(prefixClass)
          && !Chromosome.class.isAssignableFrom(prefixClass)) {
        if (!retPaths.keySet().contains(prefix)) {
          retPaths.put(prefix, index);
        }
      }
    }
    return retPaths;
  }
Пример #16
0
  public void testAddToCollection() throws Exception {
    Company c1 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
    Contractor c2 = new Contractor();
    c1.setName("Michael");
    c2.setName("Albert");

    try {
      writer.store(c1);
      writer.store(c2);

      Company c3 = (Company) writer.getObjectById(c1.getId(), Company.class);
      assertEquals(0, c3.getContractors().size());

      writer.addToCollection(c1.getId(), Company.class, "contractors", c2.getId());

      c3 = (Company) writer.getObjectById(c1.getId(), Company.class);
      assertEquals(1, c3.getContractors().size());
      assertTrue(c3.getContractors().iterator().next() instanceof Contractor);
      assertEquals(c2.getId(), ((Contractor) c3.getContractors().iterator().next()).getId());
    } finally {
      writer.delete(c1);
      writer.delete(c2);
    }
  }
  /**
   * Search for the classes in a collection for a given InterMineObject, for example find all of the
   * sub-classes of Employee in the Department.employees collection of a given Department. If there
   * are no subclasses or the collection is empty a list with the type of the collection is
   * returned.
   *
   * @param object an InterMineObject to inspect
   * @param field the name if the collection to check
   * @param os the ObjectStore in which to execute the query
   * @return a list of classes in the collection
   */
  public static List<Class<?>> queryForTypesInCollection(
      InterMineObject object, String field, ObjectStore os) {
    List<Class<?>> typesInCollection = new ArrayList<Class<?>>();

    // if there are no subclasses there can only be one type in the collection
    Model model = os.getModel();
    ClassDescriptor startCld =
        model.getClassDescriptorByName(DynamicUtil.getSimpleClassName(object));
    CollectionDescriptor col = startCld.getCollectionDescriptorByName(field, true);
    ClassDescriptor colCld = col.getReferencedClassDescriptor();

    if (model.getAllSubs(colCld).isEmpty()) {
      // there aren't any subclasses, so no need to do a query
      typesInCollection.add(colCld.getType());
    } else {
      // there may be multiple subclasses in the collection, need to run a query
      Query query = new Query();
      QueryClass qc = new QueryClass(colCld.getType());
      query.addFrom(qc);
      query.addToSelect(new QueryField(qc, "class"));
      query.setDistinct(true);
      query.setConstraint(
          new ContainsConstraint(
              new QueryCollectionReference(object, field), ConstraintOp.CONTAINS, qc));
      for (Object o : os.executeSingleton(query)) {
        typesInCollection.add((Class<?>) o);
      }

      // Collection was empty but add collection type to be consistent with collection types
      // without subclasses.
      if (typesInCollection.isEmpty()) {
        typesInCollection.add(colCld.getType());
      }
    }
    return typesInCollection;
  }
Пример #18
0
  /**
   * Read the UTRs collection of MRNA then set the fivePrimeUTR and threePrimeUTR fields with the
   * corresponding UTRs.
   *
   * @throws Exception if anything goes wrong
   */
  public void createUtrRefs() throws Exception {
    long startTime = System.currentTimeMillis();
    Query q = new Query();
    q.setDistinct(false);

    QueryClass qcMRNA = new QueryClass(model.getClassDescriptorByName("MRNA").getType());
    q.addFrom(qcMRNA);
    q.addToSelect(qcMRNA);
    q.addToOrderBy(qcMRNA);

    QueryClass qcUTR = new QueryClass(model.getClassDescriptorByName("UTR").getType());
    q.addFrom(qcUTR);
    q.addToSelect(qcUTR);
    q.addToOrderBy(qcUTR);

    QueryCollectionReference mrnaUtrsRef = new QueryCollectionReference(qcMRNA, "UTRs");
    ContainsConstraint mrnaUtrsConstraint =
        new ContainsConstraint(mrnaUtrsRef, ConstraintOp.CONTAINS, qcUTR);

    QueryObjectReference fivePrimeRef = new QueryObjectReference(qcMRNA, "fivePrimeUTR");
    ContainsConstraint fivePrimeNullConstraint =
        new ContainsConstraint(fivePrimeRef, ConstraintOp.IS_NULL);
    QueryObjectReference threePrimeRef = new QueryObjectReference(qcMRNA, "threePrimeUTR");
    ContainsConstraint threePrimeNullConstraint =
        new ContainsConstraint(threePrimeRef, ConstraintOp.IS_NULL);

    ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
    cs.addConstraint(mrnaUtrsConstraint);
    cs.addConstraint(fivePrimeNullConstraint);
    cs.addConstraint(threePrimeNullConstraint);

    q.setConstraint(cs);

    ObjectStore os = osw.getObjectStore();

    ((ObjectStoreInterMineImpl) os).precompute(q, Constants.PRECOMPUTE_CATEGORY);
    Results res = os.execute(q, 500, true, true, true);

    int count = 0;
    InterMineObject lastMRNA = null;

    InterMineObject fivePrimeUTR = null;
    InterMineObject threePrimeUTR = null;

    osw.beginTransaction();

    Class<? extends FastPathObject> fivePrimeUTRCls =
        model.getClassDescriptorByName("FivePrimeUTR").getType();

    Iterator<?> resIter = res.iterator();
    while (resIter.hasNext()) {
      ResultsRow<?> rr = (ResultsRow<?>) resIter.next();
      InterMineObject mrna = (InterMineObject) rr.get(0);
      InterMineObject utr = (InterMineObject) rr.get(1);

      if (lastMRNA != null && !mrna.getId().equals(lastMRNA.getId())) {
        // clone so we don't change the ObjectStore cache
        InterMineObject tempMRNA = PostProcessUtil.cloneInterMineObject(lastMRNA);
        if (fivePrimeUTR != null) {
          tempMRNA.setFieldValue("fivePrimeUTR", fivePrimeUTR);
          fivePrimeUTR = null;
        }
        if (threePrimeUTR != null) {
          tempMRNA.setFieldValue("threePrimeUTR", threePrimeUTR);
          threePrimeUTR = null;
        }
        osw.store(tempMRNA);
        count++;
      }

      if (DynamicUtil.isInstance(utr, fivePrimeUTRCls)) {
        fivePrimeUTR = utr;
      } else {
        threePrimeUTR = utr;
      }

      lastMRNA = mrna;
    }

    if (lastMRNA != null) {
      // clone so we don't change the ObjectStore cache
      InterMineObject tempMRNA = PostProcessUtil.cloneInterMineObject(lastMRNA);
      tempMRNA.setFieldValue("fivePrimeUTR", fivePrimeUTR);
      tempMRNA.setFieldValue("threePrimeUTR", threePrimeUTR);
      osw.store(tempMRNA);
      count++;
    }
    LOG.info(
        "Stored MRNA "
            + count
            + " times ("
            + count * 2
            + " fields set)"
            + " - took "
            + (System.currentTimeMillis() - startTime)
            + " ms.");
    osw.commitTransaction();

    // now ANALYSE tables relating to class that has been altered - may be rows added
    // to indirection tables
    if (osw instanceof ObjectStoreWriterInterMineImpl) {
      ClassDescriptor cld = model.getClassDescriptorByName("MRNA");
      DatabaseUtil.analyse(((ObjectStoreWriterInterMineImpl) osw).getDatabase(), cld, false);
    }
  }
Пример #19
0
  public void testCreateBagTable() throws Exception {
    Collection bag = new HashSet();

    bag.add(new Integer(-10000));
    bag.add(new Integer(0));
    bag.add(new Integer(10000));
    bag.add(new Long(-10000));
    bag.add(new Long(0));
    bag.add(new Long(10000));
    bag.add(new Short((short) -10000));
    bag.add(new Short((short) 0));
    bag.add(new Short((short) 10000));
    bag.add(new BigDecimal(-10000.0));
    bag.add(new BigDecimal(0.0));
    bag.add(new BigDecimal(10000.0));
    bag.add(new Float(-10000.0));
    bag.add(new Float(0.0));
    bag.add(new Float(10000.0));
    bag.add(new Double(-10000.0));
    bag.add(new Double(0.0));
    bag.add(new Double(10000.0));
    bag.add(new String());
    bag.add(new String("a String with spaces"));
    bag.add(new String("123456"));
    bag.add(new String("123456.7"));
    bag.add(new Boolean(true));
    bag.add(new Boolean(false));
    bag.add(new Date(999999));
    bag.add(new Date(100));
    Employee employee = (Employee) DynamicUtil.createObject(Collections.singleton(Employee.class));
    employee.setId(new Integer(5000));
    bag.add(employee);
    Manager manager = (Manager) DynamicUtil.createObject(Collections.singleton(Manager.class));
    manager.setId(new Integer(5001));
    bag.add(manager);
    Company company = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
    company.setId(new Integer(6000));
    bag.add(company);

    // this shouldn't appear in any table
    bag.add(BigInteger.ONE);

    DatabaseUtil.createBagTable(db, con, "integer_table", bag, Integer.class);
    DatabaseUtil.createBagTable(db, con, "long_table", bag, Long.class);
    DatabaseUtil.createBagTable(db, con, "short_table", bag, Short.class);
    DatabaseUtil.createBagTable(db, con, "bigdecimal_table", bag, BigDecimal.class);
    DatabaseUtil.createBagTable(db, con, "float_table", bag, Float.class);
    DatabaseUtil.createBagTable(db, con, "double_table", bag, Double.class);
    DatabaseUtil.createBagTable(db, con, "string_table", bag, String.class);
    DatabaseUtil.createBagTable(db, con, "boolean_table", bag, Boolean.class);
    DatabaseUtil.createBagTable(db, con, "date_table", bag, Date.class);
    DatabaseUtil.createBagTable(db, con, "intermineobject_table", bag, InterMineObject.class);
    DatabaseUtil.createBagTable(db, con, "employee_table", bag, Employee.class);

    Statement s = con.createStatement();
    ResultSet r = s.executeQuery("SELECT value FROM integer_table");
    Set result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    Set expected = new HashSet();
    expected.add(new Integer(-10000));
    expected.add(new Integer(0));
    expected.add(new Integer(10000));

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM long_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(new Long(-10000));
    expected.add(new Long(0));
    expected.add(new Long(10000));

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM short_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(new Integer((short) -10000));
    expected.add(new Integer((short) 0));
    expected.add(new Integer((short) 10000));

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM double_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(new Double(-10000.0));
    expected.add(new Double(0.));
    expected.add(new Double(10000.0));

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM float_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(new Float(-10000.0));
    expected.add(new Float(0.));
    expected.add(new Float(10000.0));

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM string_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(new String());
    expected.add(new String("a String with spaces"));
    expected.add(new String("123456"));
    expected.add(new String("123456.7"));

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM boolean_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(new Boolean(true));
    expected.add(new Boolean(false));

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM date_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(new Long(999999));
    expected.add(new Long(100));

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM intermineobject_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(employee.getId());
    expected.add(manager.getId());
    expected.add(company.getId());

    assertEquals(expected, result);

    r = s.executeQuery("SELECT value FROM employee_table");
    result = new HashSet();
    while (r.next()) {
      result.add(r.getObject(1));
    }

    expected = new HashSet();
    expected.add(employee.getId());
    expected.add(manager.getId());

    assertEquals(expected, result);
  }
Пример #20
0
  public void setUp() throws Exception {
    super.setUp();
    osd = new ObjectStoreDummyImpl();
    osd.setResultsSize(15);

    // Set up some known objects in the first 3 results rows
    department1 = new Department();
    department1.setName("Department1");
    department1.setId(new Integer(4));
    department2 = new Department();
    department2.setName("Department2");
    department2.setId(new Integer(5));
    department3 = new Department();
    department3.setName("Department3");
    department3.setId(new Integer(6));

    company1 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
    company1.setName("Company1");
    company1.setVatNumber(101);
    company1.setId(new Integer(1));
    company2 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
    company2.setName("Company2");
    company2.setVatNumber(102);
    company2.setId(new Integer(2));
    company3 = (Company) DynamicUtil.createObject(Collections.singleton(Company.class));
    company3.setName("Company3");
    company3.setVatNumber(103);
    company3.setId(new Integer(3));

    man1 = (Manager) DynamicUtil.createObject(Collections.singleton(Manager.class));
    man1.setName("Manager1");
    man1.setSeniority(new Integer(100));
    man1.setId(new Integer(1));
    man2 = (Manager) DynamicUtil.createObject(Collections.singleton(Manager.class));
    man2.setName("Manager2");
    man2.setSeniority(new Integer(200));
    man2.setId(new Integer(2));
    man3 = (CEO) DynamicUtil.createObject(Collections.singleton(CEO.class));
    man3.setName("Manager3");
    man3.setSeniority(new Integer(300));
    man3.setId(new Integer(3));
    man3.setCompany(company3);

    ResultsRow row = new ResultsRow();
    row.add(department1);
    row.add(company1);
    row.add(man1);
    osd.addRow(row);
    row = new ResultsRow();
    row.add(department2);
    row.add(company2);
    row.add(man2);
    osd.addRow(row);
    row = new ResultsRow();
    row.add(department3);
    row.add(company3);
    row.add(man3);
    osd.addRow(row);
    classKeys = new HashMap();
    FieldDescriptor fd =
        model
            .getClassDescriptorByName("org.intermine.model.testmodel.Company")
            .getFieldDescriptorByName("name");
    ArrayList<FieldDescriptor> keys = new ArrayList();
    keys.add(fd);
    classKeys.put("Company", keys);
  }
  public void testCreateSpanningLocations() throws Exception {
    Exon exon1 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
    exon1.setId(new Integer(107));
    Exon exon2 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
    exon2.setId(new Integer(108));
    Exon exon3 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
    exon3.setId(new Integer(109));

    Location exon1OnChr = createLocation(getChromosome(), exon1, "1", 51, 100, Location.class);
    exon1OnChr.setId(new Integer(1010));
    Location exon2OnChr = createLocation(getChromosome(), exon2, "1", 201, 250, Location.class);
    exon2OnChr.setId(new Integer(1011));
    Location exon3OnChr = createLocation(getChromosome(), exon3, "1", 201, 400, Location.class);
    exon3OnChr.setId(new Integer(1012));

    Transcript trans1 =
        (Transcript) DynamicUtil.createObject(Collections.singleton(Transcript.class));
    trans1.setId(new Integer(201));

    Transcript trans2 =
        (Transcript) DynamicUtil.createObject(Collections.singleton(Transcript.class));
    trans2.setId(new Integer(202));

    Location trans2OnChr = createLocation(getChromosome(), trans2, "1", 61, 300, Location.class);

    Gene gene = (Gene) DynamicUtil.createObject(Collections.singleton(Gene.class));
    gene.setId(new Integer(301));

    exon1.setTranscripts(new HashSet<Transcript>(Arrays.asList(new Transcript[] {trans1})));
    exon2.setTranscripts(new HashSet<Transcript>(Arrays.asList(new Transcript[] {trans1})));

    // the location of exon3 should be ignored by createSpanningLocations() because trans2
    // already has a location
    exon3.setTranscripts(new HashSet<Transcript>(Arrays.asList(new Transcript[] {trans2})));

    trans1.setGene(gene);
    trans2.setGene(gene);

    Set<InterMineObject> toStore =
        new HashSet<InterMineObject>(
            Arrays.asList(
                new InterMineObject[] {
                  getChromosome(),
                  gene,
                  trans1,
                  trans2,
                  exon1,
                  exon2,
                  exon3,
                  exon1OnChr,
                  exon2OnChr,
                  trans2OnChr
                }));

    for (InterMineObject imo : toStore) {
      osw.store(imo);
    }

    CalculateLocations cl = new CalculateLocations(osw);
    cl.createSpanningLocations("Transcript", "Exon", "exons");
    cl.createSpanningLocations("Gene", "Transcript", "transcripts");

    ObjectStore os = osw.getObjectStore();
    Transcript resTrans1 = (Transcript) os.getObjectById(new Integer(201));

    Assert.assertEquals(1, resTrans1.getLocations().size());
    Location resTrans1Location = (Location) resTrans1.getLocations().iterator().next();
    Assert.assertEquals(51, resTrans1Location.getStart().intValue());
    Assert.assertEquals(250, resTrans1Location.getEnd().intValue());

    Transcript resTrans2 = (Transcript) os.getObjectById(new Integer(202));

    Assert.assertEquals(1, resTrans2.getLocations().size());
    Location resTrans2Location = (Location) resTrans2.getLocations().iterator().next();
    Assert.assertEquals(61, resTrans2Location.getStart().intValue());
    Assert.assertEquals(300, resTrans2Location.getEnd().intValue());

    Gene resGene = (Gene) os.getObjectById(new Integer(301));
    Assert.assertEquals(1, resGene.getLocations().size());
    Location resGeneLocation = (Location) resGene.getLocations().iterator().next();
    Assert.assertEquals(51, resGeneLocation.getStart().intValue());
    Assert.assertEquals(300, resGeneLocation.getEnd().intValue());
  }
  private void createOverlapTestData() throws Exception {
    Chromosome chr = (Chromosome) DynamicUtil.createObject(Collections.singleton(Chromosome.class));
    chr.setPrimaryIdentifier("X");
    chr.setLength(new Integer(1000));
    chr.setId(new Integer(101));

    Set<InterMineObject> toStore = new HashSet<InterMineObject>();

    toStore.add(chr);

    int[][] exonInfo = {
      {1000, 1, 1},
      {1001, 2, 10},
      {1002, 10, 15},
      {1003, 16, 19},
      {1004, 16, 19},
      {1005, 20, 29},
      {1006, 30, 100},
      {1007, 30, 34},
      {1008, 32, 95},
      {1009, 38, 53},
      {1010, 40, 50},
      {1011, 44, 44},
      {1012, 54, 54},
      {1013, 54, 54},
      {1014, 60, 70},
      {1015, 120, 140},
      {1016, 141, 145},
      {1017, 146, 180},
      {1018, 220, 240},
      {1019, 240, 245},
      {1020, 245, 280},
    };

    Exon[] exons = new Exon[exonInfo.length];
    Location[] exonLocs = new Location[exonInfo.length];

    for (int i = 0; i < exons.length; i++) {
      exons[i] = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
      int exonId = exonInfo[i][0];
      int start = exonInfo[i][1];
      int end = exonInfo[i][2];
      exons[i].setId(new Integer(exonId));
      exons[i].setLength(new Integer(end - start + 1));
      exons[i].setChromosome(chr);
      exonLocs[i] = createLocation(chr, exons[i], "1", start, end, Location.class);
      exonLocs[i].setId(new Integer(1000 + exonId));
    }

    ReversePrimer rp =
        (ReversePrimer) DynamicUtil.createObject(Collections.singleton(ReversePrimer.class));
    rp.setId(new Integer(3000));
    rp.setLength(new Integer(100));
    rp.setChromosome(chr);

    Location rpLoc = createLocation(chr, rp, "1", 1, 100, Location.class);
    rpLoc.setId(new Integer(3001));

    toStore.add(rp);
    toStore.add(rpLoc);
    toStore.addAll(Arrays.asList(exons));
    toStore.addAll(Arrays.asList(exonLocs));

    for (InterMineObject imo : toStore) {
      osw.store(imo);
    }
  }
  public void testSetChromosomeLocationsAndLengths() throws Exception {
    Chromosome chr1 =
        (Chromosome) DynamicUtil.createObject(Collections.singleton(Chromosome.class));
    chr1.setPrimaryIdentifier("1");
    chr1.setId(new Integer(101));
    Chromosome chr2 =
        (Chromosome) DynamicUtil.createObject(Collections.singleton(Chromosome.class));
    chr1.setPrimaryIdentifier("2");
    chr1.setId(new Integer(102));

    Exon exon1 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
    exon1.setId(new Integer(107));
    exon1.setLength(new Integer(1000));
    Exon exon2 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
    exon2.setId(new Integer(108));
    Exon exon3 = (Exon) DynamicUtil.createObject(Collections.singleton(Exon.class));
    exon3.setId(new Integer(109));

    // exon 2 has two chromosome locations, shouldn't get chromosome[Location] references
    Location exon1OnChr = createLocation(chr1, exon1, "1", 51, 100, Location.class);
    exon1OnChr.setId(new Integer(1010));
    Location exon2OnChr = createLocation(chr2, exon2, "1", 201, 250, Location.class);
    exon2OnChr.setId(new Integer(1011));
    Location exon2OnChrDup = createLocation(chr1, exon2, "1", 501, 550, Location.class);
    exon2OnChrDup.setId(new Integer(1012));
    Location exon3OnChr = createLocation(chr2, exon3, "1", 601, 650, Location.class);
    exon3OnChr.setId(new Integer(1013));

    Set<InterMineObject> toStore =
        new HashSet<InterMineObject>(
            Arrays.asList(
                new InterMineObject[] {
                  chr1, chr2, exon1, exon2, exon3, exon1OnChr, exon2OnChr, exon2OnChrDup, exon3OnChr
                }));

    for (InterMineObject imo : toStore) {
      osw.store(imo);
    }

    CalculateLocations cl = new CalculateLocations(osw);
    cl.setChromosomeLocationsAndLengths();

    ObjectStore os = osw.getObjectStore();
    Exon resExon1 = (Exon) os.getObjectById(new Integer(107));
    Exon resExon2 = (Exon) os.getObjectById(new Integer(108));
    Exon resExon3 = (Exon) os.getObjectById(new Integer(109));

    assertEquals(chr1.getId(), resExon1.getChromosome().getId());
    assertEquals(exon1OnChr.getId(), resExon1.getChromosomeLocation().getId());

    assertNull(resExon2.getChromosome());
    assertNull(resExon2.getChromosomeLocation());

    assertEquals(chr2.getId(), resExon3.getChromosome().getId());
    assertEquals(exon3OnChr.getId(), resExon3.getChromosomeLocation().getId());

    // exon1 has length set so should stay as 1000, exon3 should get length 50 set from location
    assertEquals(new Integer(1000), resExon1.getLength());
    assertEquals(new Integer(50), resExon3.getLength());
    // nothing done to exon2
    assertNull(resExon2.getLength());
  }