public Set<String> getBrandNamesByNameAndUnii(String name, String unii) throws IOException { UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.fdaDrugLabelUrl) .queryParam( "search", "(openfda.unii:" + fixTerm.makeFdaSafe(unii) + ")+AND+(openfda.brand_name:" + fixTerm.makeFdaReady(fixTerm.makeFdaSafe(name)) + ")") .queryParam("count", "openfda.brand_name.exact"); this.apiKey.addToUriComponentsBuilder(builder); try { String result = rest.getForObject(builder.build().toUri(), String.class); FieldFinder finder = new FieldFinder("term"); return finder.find(result); } catch (HttpClientErrorException notFound) { if (notFound.getStatusCode() == HttpStatus.NOT_FOUND) { // server reported 404, handle it by returning no results log.warn("No brand name data found for search by name: " + name + " and unii " + unii); return Collections.emptySet(); } throw notFound; } }
@RequestMapping("/drug") public String search( @RequestParam(value = "name", defaultValue = "") String name, @RequestParam(value = "limit", defaultValue = "10") int limit, @RequestParam(value = "skip", defaultValue = "0") int skip) throws IOException { name = fixTerm.makeFdaSafe(name); if (name.length() == 0) { return "[]"; } List<DrugSearchResult> rv = new LinkedList<DrugSearchResult>(); Set<String> uniis = this.getUniisByName(name); Map<String, Set<String>> brandNames = this.getBrandNamesByNameAndUniis(name, uniis); // create full list of drug search results for (String unii : uniis) { for (String brandName : brandNames.get(unii)) { DrugSearchResult res = new DrugSearchResult(); res.setUnii(unii); res.setBrandName(brandName); rv.add(res); } } // sort the list of drug search results by custom comparator Collections.sort(rv, new DrugSearchComparator(name)); // implement skip/limit if (rv.size() > 0) { rv = rv.subList(skip, Math.min(rv.size(), skip + limit)); } // fill in details for all the results we're returning for (DrugSearchResult res : rv) { res.setRxcui(this.getRxcuiByUnii(res.getUnii())); res.setGenericName(this.getGenericNameByRxcui(res.getRxcui())); if (res.getActiveIngredients().isEmpty() && res.getGenericName() != null) { res.setActiveIngredients( new TreeSet<String>(Arrays.asList(res.getGenericName().split(", ")))); } } ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(rv); }