/** * 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); } }
/** {@inheritDoc} */ public ActionForward execute( @SuppressWarnings("unused") ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String type = request.getParameter("type"); if (type == null) { type = "webapp"; } if ("webapp".equals(type)) { response.getOutputStream().print("OK"); } else if ("query".equals(type)) { final InterMineAPI im = SessionMethods.getInterMineAPI(request.getSession()); ObjectStore os = im.getObjectStore(); Query q = new Query(); QueryClass c = new QueryClass(InterMineObject.class); q.addFrom(c); q.addToSelect(c); // Add a unique value to the select to avoid caching the query QueryValue token = new QueryValue(System.currentTimeMillis()); q.addToSelect(token); Results r = os.execute(q, 1, false, false, false); if (r.get(0) != null) { response.getOutputStream().print("OK"); } else { response.getOutputStream().print("NO RESULTS"); } } return null; }
/** {@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; }
/** * Constructor with necessary objects to generate an ObjectStore query from a PathQuery and * execute it. * * @param im intermine API * @param profile the user executing the query - for access to saved lists */ public WebResultsExecutor(InterMineAPI im, Profile profile) { os = im.getObjectStore(); bagQueryRunner = im.getBagQueryRunner(); this.profile = profile; this.im = im; bagManager = im.getBagManager(); this.summaryBatchSize = Constants.BATCH_SIZE; }
private InterMineObject getRequestedObject(InterMineAPI im, HttpServletRequest request) { String idString = request.getParameter("id"); Integer id = new Integer(Integer.parseInt(idString)); ObjectStore os = im.getObjectStore(); InterMineObject requestedObject = null; try { requestedObject = os.getObjectById(id); } catch (ObjectStoreException e) { Log.warn("Accessed report page with id: " + id + " but failed to find object.", e); } return requestedObject; }
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); } } } }
private static void runSpanValidationQuery(InterMineAPI im) { // a Map contains orgName and its chrInfo accordingly // e.g. <D.Melanogaster, (D.Melanogaster, X, 5000)...> chrInfoMap = new HashMap<String, List<ChromosomeInfo>>(); try { Query q = new Query(); QueryClass qcOrg = new QueryClass(Organism.class); QueryClass qcChr = new QueryClass(Chromosome.class); // Result columns QueryField qfOrgName = new QueryField(qcOrg, "shortName"); QueryField qfChrPID = new QueryField(qcChr, "primaryIdentifier"); QueryField qfChrLength = new QueryField(qcChr, "length"); // As in SQL SELECT ?,?,? q.addToSelect(qfOrgName); q.addToSelect(qfChrPID); q.addToSelect(qfChrLength); // As in SQL FROM ?,? q.addFrom(qcChr); q.addFrom(qcOrg); // As in SQL WHERE ? QueryObjectReference organism = new QueryObjectReference(qcChr, "organism"); ContainsConstraint ccOrg = new ContainsConstraint(organism, ConstraintOp.CONTAINS, qcOrg); q.setConstraint(ccOrg); Results results = im.getObjectStore().execute(q); // a List contains all the chrInfo (organism, chrPID, length) List<ChromosomeInfo> chrInfoList = new ArrayList<ChromosomeInfo>(); // a Set contains all the orgName Set<String> orgSet = new HashSet<String>(); // Handle results for (Iterator<?> iter = results.iterator(); iter.hasNext(); ) { ResultsRow<?> row = (ResultsRow<?>) iter.next(); String org = (String) row.get(0); String chrPID = (String) row.get(1); Integer chrLength = (Integer) row.get(2); // Add orgName to HashSet to filter out duplication orgSet.add(org); if (chrLength != null) { ChromosomeInfo chrInfo = new ChromosomeInfo(); chrInfo.setOrgName(org); chrInfo.setChrPID(chrPID); chrInfo.setChrLength(chrLength); // Add ChromosomeInfo to Arraylist chrInfoList.add(chrInfo); } } // Iterate orgSet and chrInfoList to put data in chrInfoMap which has the key as the // orgName and value as a ArrayList containing a list of chrInfo which has the same // orgName for (String o : orgSet) { // a List to store chrInfo for the same organism List<ChromosomeInfo> chrInfoSubList = new ArrayList<ChromosomeInfo>(); for (ChromosomeInfo chrInfo : chrInfoList) { if (o.equals(chrInfo.getOrgName())) { chrInfoSubList.add(chrInfo); chrInfoMap.put(o, chrInfoSubList); } } } } catch (Exception e) { e.printStackTrace(); } }
/** The method to run all the queries. */ @SuppressWarnings("rawtypes") private void queryExecutor() { // Use spanOverlapFullResultMap to store the data in the session @SuppressWarnings("unchecked") Map<String, Map<GenomicRegion, List<SpanQueryResultRow>>> spanOverlapFullResultMap = (Map<String, Map<GenomicRegion, List<SpanQueryResultRow>>>) request.getSession().getAttribute("spanOverlapFullResultMap"); if (spanOverlapFullResultMap == null) { spanOverlapFullResultMap = new HashMap<String, Map<GenomicRegion, List<SpanQueryResultRow>>>(); } Map<GenomicRegion, List<SpanQueryResultRow>> spanOverlapResultDisplayMap = Collections.synchronizedMap(new LinkedHashMap<GenomicRegion, List<SpanQueryResultRow>>()); // GBrowse track @SuppressWarnings("unchecked") Map<String, Map<GenomicRegion, LinkedHashMap<String, LinkedHashSet<GBrowseTrackInfo>>>> gbrowseFullTrackMap = (HashMap< String, Map<GenomicRegion, LinkedHashMap<String, LinkedHashSet<GBrowseTrackInfo>>>>) request.getSession().getAttribute("gbrowseFullTrackMap"); if (gbrowseFullTrackMap == null) { gbrowseFullTrackMap = new HashMap< String, Map<GenomicRegion, LinkedHashMap<String, LinkedHashSet<GBrowseTrackInfo>>>>(); } Map<GenomicRegion, LinkedHashMap<String, LinkedHashSet<GBrowseTrackInfo>>> gbrowseTrackMap = Collections.synchronizedMap( new LinkedHashMap< GenomicRegion, LinkedHashMap<String, LinkedHashSet<GBrowseTrackInfo>>>()); if (!spanOverlapFullResultMap.containsKey(spanUUIDString)) { spanOverlapFullResultMap.put(spanUUIDString, spanOverlapResultDisplayMap); request.getSession().setAttribute("spanOverlapFullResultMap", spanOverlapFullResultMap); gbrowseFullTrackMap.put(spanUUIDString, gbrowseTrackMap); request.getSession().setAttribute("gbrowseFullTrackMap", gbrowseFullTrackMap); try { Query q; for (GenomicRegion aSpan : spanList) { q = new Query(); q.setDistinct(true); String chrPID = aSpan.getChr(); Integer start = aSpan.getStart(); Integer end = aSpan.getEnd(); /* >>>>> TEST CODE <<<<< LOG.info("OrgName: " + orgName); LOG.info("chrPID: " + chrPID); LOG.info("start: " + start); LOG.info("end: " + end); LOG.info("FeatureTypes: " + ftKeys); LOG.info("Submissions: " + subKeys); >>>>> TEST CODE <<<<< */ // DB tables QueryClass qcOrg = new QueryClass(Organism.class); QueryClass qcChr = new QueryClass(Chromosome.class); QueryClass qcFeature = new QueryClass(SequenceFeature.class); QueryClass qcLoc = new QueryClass(Location.class); QueryClass qcSubmission = new QueryClass(Submission.class); QueryField qfOrgName = new QueryField(qcOrg, "shortName"); QueryField qfChrPID = new QueryField(qcChr, "primaryIdentifier"); QueryField qfFeaturePID = new QueryField(qcFeature, "primaryIdentifier"); QueryField qfFeatureId = new QueryField(qcFeature, "id"); QueryField qfFeatureClass = new QueryField(qcFeature, "class"); QueryField qfSubmissionTitle = new QueryField(qcSubmission, "title"); QueryField qfSubmissionDCCid = new QueryField(qcSubmission, "DCCid"); QueryField qfChr = new QueryField(qcChr, "primaryIdentifier"); QueryField qfLocStart = new QueryField(qcLoc, "start"); QueryField qfLocEnd = new QueryField(qcLoc, "end"); q.addToSelect(qfFeatureId); q.addToSelect(qfFeaturePID); q.addToSelect(qfFeatureClass); q.addToSelect(qfChr); q.addToSelect(qfLocStart); q.addToSelect(qfLocEnd); q.addToSelect(qfSubmissionDCCid); q.addToSelect(qfSubmissionTitle); q.addFrom(qcChr); q.addFrom(qcOrg); q.addFrom(qcFeature); q.addFrom(qcLoc); q.addFrom(qcSubmission); q.addToOrderBy(qfLocStart, "ascending"); ConstraintSet constraints = new ConstraintSet(ConstraintOp.AND); q.setConstraint(constraints); // SequenceFeature.organism = Organism QueryObjectReference organism = new QueryObjectReference(qcFeature, "organism"); ContainsConstraint ccOrg = new ContainsConstraint(organism, ConstraintOp.CONTAINS, qcOrg); constraints.addConstraint(ccOrg); // Organism.name = orgName SimpleConstraint scOrg = new SimpleConstraint(qfOrgName, ConstraintOp.EQUALS, new QueryValue(orgName)); constraints.addConstraint(scOrg); // Location.feature = SequenceFeature QueryObjectReference locSubject = new QueryObjectReference(qcLoc, "feature"); ContainsConstraint ccLocSubject = new ContainsConstraint(locSubject, ConstraintOp.CONTAINS, qcFeature); constraints.addConstraint(ccLocSubject); // Location.locatedOn = Chromosome QueryObjectReference locObject = new QueryObjectReference(qcLoc, "locatedOn"); ContainsConstraint ccLocObject = new ContainsConstraint(locObject, ConstraintOp.CONTAINS, qcChr); constraints.addConstraint(ccLocObject); // Chromosome.primaryIdentifier = chrPID SimpleConstraint scChr = new SimpleConstraint(qfChrPID, ConstraintOp.EQUALS, new QueryValue(chrPID)); constraints.addConstraint(scChr); // SequenceFeature.submissions = Submission QueryCollectionReference submission = new QueryCollectionReference(qcFeature, "submissions"); ContainsConstraint ccSubmission = new ContainsConstraint(submission, ConstraintOp.CONTAINS, qcSubmission); constraints.addConstraint(ccSubmission); // SequenceFeature.class in a list constraints.addConstraint(new BagConstraint(qfFeatureClass, ConstraintOp.IN, ftKeys)); // Submission.CCDid in a list constraints.addConstraint(new BagConstraint(qfSubmissionDCCid, ConstraintOp.IN, subKeys)); OverlapRange overlapInput = new OverlapRange(new QueryValue(start), new QueryValue(end), locObject); OverlapRange overlapFeature = new OverlapRange( new QueryField(qcLoc, "start"), new QueryField(qcLoc, "end"), locObject); OverlapConstraint oc = new OverlapConstraint(overlapInput, ConstraintOp.OVERLAPS, overlapFeature); constraints.addConstraint(oc); Results results = im.getObjectStore().execute(q); /* >>>>> TEST CODE <<<<< LOG.info("Query: " + q.toString()); LOG.info("Result Size: " + results.size()); LOG.info("Result >>>>> " + results); >>>>> TEST CODE <<<<< */ List<SpanQueryResultRow> spanResults = new ArrayList<SpanQueryResultRow>(); if (results == null || results.isEmpty()) { spanOverlapResultDisplayMap.put(aSpan, null); gbrowseTrackMap.put(aSpan, null); } else { for (Iterator<?> iter = results.iterator(); iter.hasNext(); ) { ResultsRow<?> row = (ResultsRow<?>) iter.next(); SpanQueryResultRow aRow = new SpanQueryResultRow(); aRow.setFeatureId((Integer) row.get(0)); aRow.setFeaturePID((String) row.get(1)); aRow.setFeatureClass(((Class) row.get(2)).getSimpleName()); aRow.setChr((String) row.get(3)); aRow.setStart((Integer) row.get(4)); aRow.setEnd((Integer) row.get(5)); aRow.setSubDCCid((String) row.get(6)); aRow.setSubTitle((String) row.get(7)); spanResults.add(aRow); } spanOverlapResultDisplayMap.put(aSpan, spanResults); gbrowseTrackMap.put(aSpan, getSubGbrowseTrack(spanResults)); // Gbrowse } } } catch (Exception e) { e.printStackTrace(); } } }
/** {@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; }
@Override public void display(HttpServletRequest request, ReportObject reportObject) { // get the gene/protein in question from the request InterMineObject object = reportObject.getObject(); // API connection HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); Model model = im.getModel(); PathQuery query = new PathQuery(model); // cast me Gene Gene gene = (Gene) object; Object genePrimaryIDObj = gene.getPrimaryIdentifier(); if (genePrimaryIDObj != null) { // fetch the expression String genePrimaryID = String.valueOf(genePrimaryIDObj); query = geneExpressionAtlasQuery(genePrimaryID, query); // execute the query Profile profile = SessionMethods.getProfile(session); PathQueryExecutor executor = im.getPathQueryExecutor(profile); ExportResultsIterator values = executor.execute(query); // convert to a map GeneExpressionAtlasDiseasesExpressions geae = new GeneExpressionAtlasDiseasesExpressions(values); // attach to results request.setAttribute("expressions", geae); request.setAttribute("url", "http://www.ebi.ac.uk/gxa/experiment/E-MTAB-62/" + genePrimaryID); request.setAttribute("defaultPValue", "1e-4"); request.setAttribute("defaultTValue", "4"); // get the corresponding collection for (FieldDescriptor fd : reportObject.getClassDescriptor().getAllFieldDescriptors()) { if ("atlasExpression".equals(fd.getName()) && fd.isCollection()) { // fetch the collection Collection<?> collection = null; try { collection = (Collection<?>) reportObject.getObject().getFieldValue("atlasExpression"); } catch (IllegalAccessException e) { e.printStackTrace(); } List<Class<?>> lc = PathQueryResultHelper.queryForTypesInCollection( reportObject.getObject(), "atlasExpression", im.getObjectStore()); // create an InlineResultsTable InlineResultsTable t = new InlineResultsTable( collection, fd.getClassDescriptor().getModel(), SessionMethods.getWebConfig(request), im.getClassKeys(), collection.size(), false, lc); request.setAttribute("collection", t); break; } } } }
/** {@inheritDoc} */ @SuppressWarnings("unused") @Override public ActionForward execute( @SuppressWarnings("unused") ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { long startTime = System.currentTimeMillis(); HttpSession session = request.getSession(); InterMineAPI im = SessionMethods.getInterMineAPI(session); if (im.getBagManager().isAnyBagToUpgrade(SessionMethods.getProfile(session))) { recordError(new ActionMessage("login.upgradeListManually"), request); } // fetch & set requested object InterMineObject requestedObject = getRequestedObject(im, request); if (requestedObject != null) { ReportObjectFactory reportObjectFactory = SessionMethods.getReportObjects(session); ReportObject reportObject = reportObjectFactory.get(requestedObject); request.setAttribute("object", reportObject); request.setAttribute("reportObject", reportObject); request.setAttribute("requestedObject", requestedObject); // hell starts here TagManager tagManager = im.getTagManager(); ServletContext servletContext = session.getServletContext(); ObjectStore os = im.getObjectStore(); String superuser = im.getProfileManager().getSuperuser(); if (superuser.equals(SessionMethods.getProfile(session).getUsername())) { request.setAttribute("SHOW_TAGS", true); } // place InlineLists based on TagManager, reportObject is cached while Controller is not Map<String, List<InlineList>> placedInlineLists = new TreeMap<String, List<InlineList>>(); // traverse all unplaced (non-header) InlineLists for (InlineList list : reportObject.getNormalInlineLists()) { FieldDescriptor fd = list.getDescriptor(); String taggedType = getTaggedType(fd); // assign lists to any aspects they are tagged to or put in unplaced lists String fieldPath = fd.getClassDescriptor().getUnqualifiedName() + "." + fd.getName(); List<Tag> tags = tagManager.getTags(null, fieldPath, taggedType, superuser); for (Tag tag : tags) { String tagName = tag.getTagName(); if (AspectTagUtil.isAspectTag(tagName)) { List<InlineList> listsForAspect = placedInlineLists.get(tagName); if (listsForAspect == null) { listsForAspect = new ArrayList<InlineList>(); placedInlineLists.put(tagName, listsForAspect); } listsForAspect.add(list); } else if (tagName.equals(TagNames.IM_SUMMARY)) { List<InlineList> summaryLists = placedInlineLists.get(tagName); if (summaryLists == null) { summaryLists = new ArrayList<InlineList>(); placedInlineLists.put(tagName, summaryLists); } summaryLists.add(list); } } } // any lists that aren't tagged will be 'unplaced' List<InlineList> unplacedInlineLists = new ArrayList<InlineList>(reportObject.getNormalInlineLists()); unplacedInlineLists.removeAll(placedInlineLists.values()); long now = System.currentTimeMillis(); LOG.info("TIME placed inline lists: " + (now - startTime) + "ms"); long stepTime = now; request.setAttribute("mapOfInlineLists", placedInlineLists); request.setAttribute("listOfUnplacedInlineLists", unplacedInlineLists); Map<String, Map<String, DisplayField>> placementRefsAndCollections = new TreeMap<String, Map<String, DisplayField>>(); Set<String> aspects = new LinkedHashSet<String>(SessionMethods.getCategories(servletContext)); Set<ClassDescriptor> cds = os.getModel().getClassDescriptorsForClass(requestedObject.getClass()); for (String aspect : aspects) { placementRefsAndCollections.put( TagNames.IM_ASPECT_PREFIX + aspect, new TreeMap<String, DisplayField>(String.CASE_INSENSITIVE_ORDER)); } Map<String, DisplayField> miscRefs = new TreeMap<String, DisplayField>(reportObject.getRefsAndCollections()); placementRefsAndCollections.put(TagNames.IM_ASPECT_MISC, miscRefs); // summary refs and colls Map<String, DisplayField> summaryRefsCols = new TreeMap<String, DisplayField>(); placementRefsAndCollections.put(TagNames.IM_SUMMARY, summaryRefsCols); for (Iterator<Entry<String, DisplayField>> iter = reportObject.getRefsAndCollections().entrySet().iterator(); iter.hasNext(); ) { Map.Entry<String, DisplayField> entry = iter.next(); DisplayField df = entry.getValue(); if (df instanceof DisplayReference) { categoriseBasedOnTags( ((DisplayReference) df).getDescriptor(), "reference", df, miscRefs, tagManager, superuser, placementRefsAndCollections, SessionMethods.isSuperUser(session)); } else if (df instanceof DisplayCollection) { categoriseBasedOnTags( ((DisplayCollection) df).getDescriptor(), "collection", df, miscRefs, tagManager, superuser, placementRefsAndCollections, SessionMethods.isSuperUser(session)); } } // remove any fields overridden by displayers removeFieldsReplacedByReportDisplayers(reportObject, placementRefsAndCollections); request.setAttribute("placementRefsAndCollections", placementRefsAndCollections); String type = reportObject.getType(); request.setAttribute("objectType", type); String stableLink = PortalHelper.generatePortalLink(reportObject.getObject(), im, request); if (stableLink != null) { request.setAttribute("stableLink", stableLink); } stepTime = System.currentTimeMillis(); startTime = stepTime; // attach only non empty categories Set<String> allClasses = new HashSet<String>(); for (ClassDescriptor cld : cds) { allClasses.add(cld.getUnqualifiedName()); } TemplateManager templateManager = im.getTemplateManager(); Map<String, List<ReportDisplayer>> displayerMap = reportObject.getReportDisplayers(); stepTime = System.currentTimeMillis(); startTime = stepTime; List<String> categories = new LinkedList<String>(); for (String aspect : aspects) { // 1) Displayers // 2) Inline Lists if ((displayerMap != null && displayerMap.containsKey(aspect)) || placedInlineLists.containsKey(aspect)) { categories.add(aspect); } else { // 3) Templates if (!templateManager.getReportPageTemplatesForAspect(aspect, allClasses).isEmpty()) { categories.add(aspect); } else { // 4) References & Collections if (placementRefsAndCollections.containsKey("im:aspect:" + aspect) && placementRefsAndCollections.get("im:aspect:" + aspect) != null) { for (DisplayField df : placementRefsAndCollections.get("im:aspect:" + aspect).values()) { categories.add(aspect); break; } } } } } if (!categories.isEmpty()) { request.setAttribute("categories", categories); } now = System.currentTimeMillis(); LOG.info("TIME made list of categories: " + (now - stepTime) + "ms"); } return null; }