Commit baa57ba4 authored by Matija Obreza's avatar Matija Obreza
Browse files

Filtering 1

parent 2aa362b5
......@@ -74,10 +74,14 @@ public interface AccessionRepository extends JpaRepository<Accession, Long> {
@Query("from Accession a where a.id in ( ?1 )")
Page<Accession> findById(Collection<Long> accessionIds, Pageable pageable);
@Query("from Accession a where a.id in ( ?1 )")
List<Accession> listById(Collection<Long> accessionIds);
Page<Accession> findByInstituteAndTaxonomy(FaoInstitute institute, Taxonomy taxonomy, Pageable pageable);
Page<Accession> findByTaxonomy(Taxonomy taxonomy, Pageable pageable);
@Query("select a from Accession a where a.taxonomy in ( ?1 )")
Page<Accession> findByTaxonomy(Collection<Taxonomy> taxonomies, Pageable pageable);
}
package org.crophub.rest.common.service;
import org.crophub.rest.common.model.genesys.Accession;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.fasterxml.jackson.databind.JsonNode;
public interface GenesysFilterService {
Page<Accession> listAccessions(JsonNode jsonTree, Pageable pageable);
}
package org.crophub.rest.common.service.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import javax.sql.DataSource;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.crophub.rest.common.model.genesys.Accession;
import org.crophub.rest.common.persistence.domain.AccessionRepository;
import org.crophub.rest.common.persistence.domain.TraitValueRepository;
import org.crophub.rest.common.service.GenesysFilterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
@Service
@Transactional(readOnly = true)
public class GenesysFilterServiceImpl implements GenesysFilterService {
public static final Log LOG = LogFactory.getLog(GenesysFilterServiceImpl.class);
@Autowired
private TraitValueRepository traitValueRepository;
@Autowired
private AccessionRepository accessionRepository;
// @PersistenceContext
// private EntityManager entityManager;
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDataSource(final DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public Page<Accession> listAccessions(JsonNode jsonTree, Pageable pageable) {
Iterator<Entry<String, JsonNode>> fields = jsonTree.fields();
while (fields.hasNext()) {
Entry<String, JsonNode> entry = fields.next();
LOG.debug("Looking at " + entry.getKey() + " = " + entry.getValue());
}
List<Object> params = new ArrayList<Object>();
StringBuffer sb = new StringBuffer();
sb.append(" from accession a ");
if (jsonTree.has("taxonomy")) {
sb.append(" inner join all_taxonomy t on t.Taxon_Code=a.Taxon_Code ");
}
if (jsonTree.has("lat") || jsonTree.has("lon") || jsonTree.has("alt")) {
sb.append(" inner join all_environment env on env.ALIS_Id=a.id ");
}
createQuery(sb, "a.Origin", jsonTree.get("origin"), params);
createQuery(sb, "a.Institute", jsonTree.get("institute"), params);
createQuery(sb, "t.Genus", jsonTree.get("taxonomy"), params);
createQuery(sb, "env.LongitudeD", jsonTree.get("lon"), params);
createQuery(sb, "env.LatitudeD", jsonTree.get("lat"), params);
createQuery(sb, "env.Altitude", jsonTree.get("alt"), params);
LOG.info("Parameter count: " + params.size());
LOG.info("Count query:\n" + sb.toString());
Long totalCount = this.jdbcTemplate.queryForObject("select count(a.id) " + sb.toString(), params.toArray(), Long.class);
LOG.info("Total count: " + totalCount);
if (pageable.getSort() != null) {
sb.append("\n order by ");
for (Order o : pageable.getSort()) {
LOG.debug("Order: " + o);
// ClassMetadata md =
// sessionFactory.getClassMetadata(Accession.class);
// md.
// EntityType<Accession> x =
// entityManager.getMetamodel().entity(Accession.class);
// System.err.println(x.getAttribute(o.getProperty()).getName());
// sb.append(x.getAttribute(o.getProperty()).getName());
sb.append("a.").append(o.getProperty());
sb.append(" ").append(o.getDirection());
}
}
sb.append(" limit ");
LOG.debug("Pageable=" + pageable.getOffset() + " " + pageable.getPageNumber());
sb.append(pageable.getOffset());
sb.append(", ");
sb.append(pageable.getPageSize());
LOG.info("Filter query:\n" + sb.toString());
LOG.info("Parameter count: " + params.size());
LOG.info("Params: " + ArrayUtils.toString(params.toArray()));
// List<Accession> results = this.jdbcTemplate.query(sb.toString(), new
// Object[] {}, new BeanPropertyRowMapper<Accession>(Accession.class));
LOG.info("Getting IDs");
List<Long> results = this.jdbcTemplate.queryForList("select a.id " + sb.toString(), params.toArray(), Long.class);
LOG.info("Getting accessions");
return new PageImpl<Accession>(results.size() == 0 ? new ArrayList<Accession>() : accessionRepository.listById(results), pageable, totalCount);
}
private void createQuery(StringBuffer sb, String dbName, JsonNode fieldQuery, List<Object> params) {
LOG.debug("Handling " + dbName);
if (fieldQuery != null) {
LOG.debug("Adding " + fieldQuery + " sz=" + fieldQuery.size());
if (params.size() == 0)
sb.append(" where ");
else
sb.append(" and ");
// if (fieldQuery.getNodeType() == JsonNodeType.ARRAY) {
sb.append("\n ").append(dbName);
if (fieldQuery.size() <= 1)
sb.append(" = ");
else
sb.append(" IN (");
if (fieldQuery.size() > 1) {
int i = 0;
for (JsonNode x : fieldQuery) {
if (i > 0) {
sb.append(",?");
} else {
sb.append("?");
}
LOG.debug(" + " + x + " " + x.getNodeType());
addParam(params, x);
i++;
}
} else {
sb.append("?");
addParam(params, fieldQuery);
}
if (fieldQuery.size() > 1)
sb.append(") ");
// }
}
}
private void addParam(List<Object> params, JsonNode value) {
if (JsonNodeType.STRING == value.getNodeType())
params.add(value.asText());
else if (JsonNodeType.BOOLEAN == value.getNodeType())
params.add(value.asBoolean());
else if (JsonNodeType.NUMBER == value.getNodeType())
params.add(value.asDouble());
}
}
/**
* Copyright 2013 Global Crop Diversity Trust
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
package org.crophub.rest.servlet.controller;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;
import org.crophub.rest.common.model.genesys.Accession;
import org.crophub.rest.common.service.GenesysFilterService;
import org.crophub.rest.common.service.GenesysService;
import org.crophub.rest.common.service.InstituteService;
import org.crophub.rest.common.service.TaxonomyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
@Scope("request")
@RequestMapping("/acn")
public class FilterController extends BaseController {
@Autowired
private SelectionBean selectionBean;
@Autowired
private InstituteService instituteService;
@Autowired
private GenesysService genesysService;
@Autowired
private GenesysFilterService filterService;
@Autowired
private TaxonomyService taxonomyService;
/**
* Browse all
*
* @param model
* @param page
* @return
*/
@RequestMapping("/f")
public String viewFiltered(ModelMap model, @RequestParam(value = "page", required = false, defaultValue = "1") int page,
@RequestParam(value = "filter", required = false, defaultValue = "") String jsonFilter) {
_logger.info("Filtering by: " + jsonFilter);
ObjectMapper mapper=new ObjectMapper();
JsonNode jsonTree = null;
try {
jsonTree = mapper.readTree(jsonFilter);
_logger.debug(jsonTree.toString());
Iterator<Entry<String, JsonNode>> fields = jsonTree.fields();
while (fields.hasNext()) {
Entry<String, JsonNode> entry = fields.next();
_logger.debug("2=" + entry.getKey() + " = " + entry.getValue());
}
} catch (IOException e) {
e.printStackTrace();
}
Page<Accession> accessions = filterService.listAccessions(jsonTree, new PageRequest(page - 1, 50, new Sort("ACC_Numb_HI")));
_logger.info("Got: " + accessions);
model.addAttribute("filter", jsonTree.toString());
model.addAttribute("pagedData", accessions);
model.addAttribute("selection", selectionBean);
return "/accession/data";
}
}
......@@ -24,7 +24,7 @@ db.url=jdbc:mysql://127.0.0.1/pgrsys_genesys?useUnicode=true&characterEncoding=U
db.driverClassName = com.mysql.jdbc.Driver
db.username = root
db.password =
db.showSql=true
db.showSql=false
c3p0.acquireIncrement=1
c3p0.minPoolSize=5
......
......@@ -48,7 +48,8 @@
<spring:message code="accessions.number" arguments="${pagedData.totalElements}" />
<br />
<spring:message code="paged.pageOfPages" arguments="${pagedData.number+1},${pagedData.totalPages}" />
<a class="${pagedData.number eq 0 ? 'disabled' :''}" href="?page=${pagedData.number eq 0 ? 1 : pagedData.number}">⇇ Previous</a> <a href="?page=${pagedData.number + 2}">Next ⇉</a>
<a class="${pagedData.number eq 0 ? 'disabled' :''}" href="?page=${pagedData.number eq 0 ? 1 : pagedData.number}">⇇ Previous</a>
<a href="<spring:url value=""><spring:param name="page" value="${pagedData.number+2}" /><spring:param name="filter" value="${filter}" /></spring:url>">Next ⇉</a>
</div>
<table class="accessions">
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment