public void setUp() throws Exception { super.setUp(); userprofileOS.setModel(Model.getInstanceByName("userprofile")); Model testmodel = Model.getInstanceByName("testmodel"); query = new PathQuery(testmodel); query.addView("Employee"); query.addView("Employee.name"); queryBag = new PathQuery(testmodel); queryBag.addView("Employee"); queryBag.addView("Employee.name"); queryBag.addConstraint(Constraints.in("Employee", "bag2")); sq = new SavedQuery("query1", date, query); sqBag = new SavedQuery("query3", date, queryBag); hist = new SavedQuery("query2", date, (PathQuery) query.clone()); hist2 = new SavedQuery("query1", date, query.clone()); template = new TemplateQuery("template", "ttitle", "tdesc", new PathQuery(testmodel)); SessionMethods.initSession(this.getSession()); Profile profile = (Profile) getSession().getAttribute(Constants.PROFILE); profile.saveQuery(sq.getName(), sq); profile.saveQuery(sqBag.getName(), sqBag); profile.saveHistory(hist); profile.saveHistory(hist2); }
@AfterClass public static void shutdown() { int deleted = 0; if (osw != null) { try { osw.beginTransaction(); PathQuery pq = new PathQuery(osw.getModel()); pq.addView("Types.id"); pq.addConstraint(Constraints.eq("Types.name", "histo*")); Query q = MainHelper.makeQuery(pq, new HashMap(), new HashMap(), null, new HashMap()); Results res = osw.execute(q, 50000, true, false, true); for (Object row : res) { Types thing = (Types) ((List) row).get(0); osw.delete(thing); deleted++; } osw.commitTransaction(); } catch (ObjectStoreException e) { LOG.warn(e); } try { osw.close(); } catch (ObjectStoreException e) { LOG.warn(e); } } System.out.printf("\n[CLEAN UP] Deleted %d things\n", deleted); }
@SuppressWarnings("unchecked") @Override public boolean removeAll(@SuppressWarnings("rawtypes") Collection c) { int priorSize = getSize(); if (c instanceof ItemList) { ItemList res = subtract(((ItemList) c)); update(res); delete(); res.rename(getName()); } else if (!c.isEmpty()) { try { Item[] is = (Item[]) c.toArray(new Item[0]); String path = is[0].getType() + ".id"; PathQuery pq = new PathQuery(services.getModel()); pq.addView(path); pq.addConstraint( Constraints.oneOfValues( path, collect( collect(Arrays.asList(is), invokerTransformer("getId")), stringValueTransformer()))); createListAndSubtract(pq); } catch (ArrayStoreException e) { // Do nothing - we didn't get a collection of items. } } return priorSize != getSize(); }
/** * Used for making a query for a reference or collection. Only used when a user clicks on [show * all] under an inline table on an Object's report page. The type of that object is * "startingPath", eg. Department. This path will be prepended to every path in the query. The * "type" is the type of the reference/collection, eg. Employee. * * <p>TODO use getDefaultViewForClass() instead * * @param objType class of object we are querying for eg. Manager * @param model the model * @param webConfig the webconfig * @param fieldType the type of the field this object is in, eg Employee * @return query, eg. Department.employees.name */ protected static PathQuery getQueryWithDefaultView( String objType, Model model, WebConfig webConfig, String fieldType) { String prefix = fieldType; PathQuery query = new PathQuery(model); ClassDescriptor cld = model.getClassDescriptorByName(objType); List<FieldConfig> fieldConfigs = getClassFieldConfigs(webConfig, cld); if (!StringUtils.isBlank(prefix)) { try { // if the type is different to the end of the prefix path, add a subclass constraint Path fieldPath = new Path(model, fieldType); String fieldEndType = TypeUtil.unqualifiedName(fieldPath.getEndType().getName()); if (!fieldEndType.equals(objType)) { query.addConstraint(Constraints.type(fieldType, objType)); } } catch (PathException e) { LOG.error("Invalid path configured in webconfig for class: " + objType); } } for (FieldConfig fieldConfig : fieldConfigs) { if (fieldConfig.getShowInResults()) { String path = prefix + "." + fieldConfig.getFieldExpr(); int from = prefix.length() + 1; while (path.indexOf('.', from) != -1) { int dotPos = path.indexOf('.', from); int nextDot = path.indexOf('.', dotPos + 1); String outerJoin = nextDot == -1 ? path.substring(0, dotPos) : path.substring(0, nextDot); query.setOuterJoinStatus(outerJoin, OuterJoinStatus.OUTER); from = dotPos + 1; } query.addView(path); } } if (query.getView().size() == 0) { for (AttributeDescriptor att : cld.getAllAttributeDescriptors()) { if (!"id".equals(att.getName())) { query.addView(prefix + "." + att.getName()); } } } return query; }
@Override public boolean remove(Object i) { int priorSize = getSize(); if (i instanceof Item) { Item item = (Item) i; String path = item.getType() + ".id"; PathQuery pq = new PathQuery(services.getModel()); pq.addView(path); pq.addConstraint(Constraints.eq(path, Integer.toString(item.getId()))); createListAndSubtract(pq); } return priorSize != getSize(); }
/** * Tell the requester about all the reference sequences that have data (are of non-zero length) * and are in the correct domain. */ private void serveRefSeqs() { Model m = im.getModel(); ClassDescriptor ref = m.getClassDescriptorByName(refType); if (ref == null) { throw new ResourceNotFoundException("No class called " + ref); } PathQuery pq = new PathQuery(m); pq.addView(refType + ".id"); pq.addConstraint(Constraints.greaterThan(refType + "." + lengthPath, "0")); pq.addConstraint(Constraints.eq(refType + "." + domainPath, domain)); Query q = pathQueryToOSQ(pq); SingletonResults res = im.getObjectStore().executeSingleton(q); if (res.size() == 0) { throw new ResourceNotFoundException("No " + refType + "s on " + domain); } Iterator<Object> it = res.iterator(); while (it.hasNext()) { FastPathObject o = (FastPathObject) it.next(); Map<String, Object> refseq = makeRefSeq(o); addResultItem(refseq, it.hasNext()); } }
/** {@inheritDoc} */ @Override public ActionForward execute( ComponentContext context, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { boolean canExportAsBED = false; HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Model model = im.getModel(); PathQuery query = new PathQuery(model); // org and dbkey for galaxy use Set<String> orgSet = new HashSet<String>(); Set<String> genomeBuildSet = new HashSet<String>(); // Build GenomicRegion pathquery, the request is from GenomicRegionSearch "export to Galaxy" if (request.getParameter("featureIds") != null) { String featureIds = request.getParameter("featureIds").trim(); String orgName = request.getParameter("orgName"); if (orgName != null && !"".equals(orgName)) { orgSet.add(orgName); } // Refer to GenomicRegionSearchService.getExportFeaturesQuery method String path = "SequenceFeature"; query.addView(path + ".primaryIdentifier"); query.addView(path + ".chromosomeLocation.locatedOn.primaryIdentifier"); query.addView(path + ".chromosomeLocation.start"); query.addView(path + ".chromosomeLocation.end"); query.addView(path + ".organism.name"); // use ids or pids String[] idsInStr = featureIds.split(","); Set<Integer> ids = new HashSet<Integer>(); boolean isIds = true; for (String id : idsInStr) { id = id.trim(); if (!Pattern.matches("^\\d+$", id)) { isIds = false; break; } ids.add(Integer.valueOf(id)); } if (isIds) { query.addConstraint(Constraints.inIds(path, ids)); } else { if (featureIds.contains("'")) { featureIds = featureIds.replaceAll("'", "\\\\'"); } query.addConstraint(Constraints.lookup(path, featureIds, null)); } canExportAsBED = true; } else { // request from normal result table String tableName = request.getParameter("table"); request.setAttribute("table", tableName); PagedTable pt = SessionMethods.getResultsTable(session, tableName); // Null check to page table, maybe session timeout? if (pt == null) { LOG.error("Page table is NULL..."); return null; } // Check if can export as BED TableHttpExporter tableExporter = new BEDHttpExporter(); try { canExportAsBED = tableExporter.canExport(pt); } catch (Exception e) { canExportAsBED = false; LOG.error("Caught an error running canExport() for: BEDHttpExporter. " + e); e.printStackTrace(); } LinkedHashMap<Path, Integer> exportClassPathsMap = getExportClassPaths(pt); List<Path> exportClassPaths = new ArrayList<Path>(exportClassPathsMap.keySet()); Map<String, String> pathMap = new LinkedHashMap<String, String>(); for (Path path : exportClassPaths) { String pathString = path.toStringNoConstraints(); String displayPath = pathString.replace(".", " > "); pathMap.put(pathString, displayPath); } Map<String, Integer> pathIndexMap = new LinkedHashMap<String, Integer>(); for (int index = 0; index < exportClassPaths.size(); index++) { String pathString = exportClassPaths.get(index).toStringNoConstraints(); Integer idx = exportClassPathsMap.get(exportClassPaths.get(index)); pathIndexMap.put(pathString, idx); } request.setAttribute("exportClassPaths", pathMap); request.setAttribute("pathIndexMap", pathIndexMap); // Support export public and private lists to Galaxy query = pt.getWebTable().getPathQuery(); ObjectStore os = im.getObjectStore(); Map<PathConstraint, String> constrains = query.getConstraints(); for (PathConstraint constraint : constrains.keySet()) { if (constraint instanceof PathConstraintBag) { String bagName = ((PathConstraintBag) constraint).getBag(); InterMineBag imBag = im.getBagManager().getBag(SessionMethods.getProfile(session), bagName); // find the classKeys Set<String> classKeySet = new LinkedHashSet<String>(); for (Integer id : imBag.getContentsAsIds()) { String classKey = pt.findClassKeyValue(im.getClassKeys(), os.getObjectById(id)); classKeySet.add(classKey); } String path = ((PathConstraintBag) constraint).getPath(); // replace constraint in the pathquery PathConstraintLookup newConstraint = new PathConstraintLookup( path, classKeySet.toString().substring(1, classKeySet.toString().length() - 1), null); query.replaceConstraint(constraint, newConstraint); } } orgSet = SequenceFeatureExportUtil.getOrganisms(query, session); } if (query instanceof TemplateQuery) { TemplateQuery templateQuery = (TemplateQuery) query; Map<PathConstraint, SwitchOffAbility> constraintSwitchOffAbilityMap = templateQuery.getConstraintSwitchOffAbility(); for (Map.Entry<PathConstraint, SwitchOffAbility> entry : constraintSwitchOffAbilityMap.entrySet()) { if (entry.getValue().compareTo(SwitchOffAbility.OFF) == 0) { templateQuery.removeConstraint(entry.getKey()); } } } String queryXML = PathQueryBinding.marshal(query, "", model.getName(), PathQuery.USERPROFILE_VERSION); // String encodedQueryXML = URLEncoder.encode(queryXML, "UTF-8"); String tableViewURL = new URLGenerator(request).getPermanentBaseURL() + "/service/query/results"; request.setAttribute("tableURL", tableViewURL); request.setAttribute("queryXML", queryXML); request.setAttribute("size", 1000000); // If can export as BED request.setAttribute("canExportAsBED", canExportAsBED); if (canExportAsBED) { String bedURL = new URLGenerator(request).getPermanentBaseURL() + "/service/query/results/bed"; request.setAttribute("bedURL", bedURL); genomeBuildSet = (Set<String>) OrganismGenomeBuildLookup.getGenomeBuildByOrgansimCollection(orgSet); String org = (orgSet.size() < 1) ? "Organism information not available" : StringUtil.join(orgSet, ","); // possible scenario: [null, ce3, null], should remove all null element and then join genomeBuildSet.removeAll(Collections.singleton(null)); String dbkey = (genomeBuildSet.size() < 1) ? "Genome Build information not available" : StringUtil.join(genomeBuildSet, ","); request.setAttribute("org", org); request.setAttribute("dbkey", dbkey); } // PathMap Map<String, String> pathsMap = new LinkedHashMap<String, String>(); List<String> views = query.getView(); for (String view : views) { String title = query.getGeneratedPathDescription(view); title = WebUtil.formatColumnName(title); pathsMap.put(view, title); } request.setAttribute("pathsMap", pathsMap); return null; }