Example usage for org.springframework.web.servlet.support RequestContextUtils getLocale

List of usage examples for org.springframework.web.servlet.support RequestContextUtils getLocale

Introduction

In this page you can find the example usage for org.springframework.web.servlet.support RequestContextUtils getLocale.

Prototype

public static Locale getLocale(HttpServletRequest request) 

Source Link

Document

Retrieve the current locale from the given request, using the LocaleResolver bound to the request by the DispatcherServlet (if available), falling back to the request's accept-header Locale.

Usage

From source file:org.gbif.portal.web.content.geospatial.GeospatialIntroProvider.java

/**
 * @see org.gbif.portal.web.content.ContentProvider#addContent(org.gbif.portal.web.content.ContentView)
 *///from  w  w  w.  j a v a2  s.c  o m
public void addContent(ContentView contentView, HttpServletRequest request, HttpServletResponse response) {

    String remoteAddr = request.getRemoteAddr();
    if (logger.isDebugEnabled()) {
        logger.debug("Remote user address:" + remoteAddr);
    }
    try {
        Locale locale = RequestContextUtils.getLocale(request);
        CountryDTO country = geospatialManager.getCountryForIsoCountryCode("CO", locale);
        int speciesCountryCO = country.getSpeciesCount();
        int totalOcurrenceRecordsCO = country.getOccurrenceCount();
        contentView.addObject("totalOcurrenceRecordsCO", totalOcurrenceRecordsCO);
        contentView.addObject("speciesCountryCO", speciesCountryCO);
    } catch (Exception e) {
        logger.error("Occurrence count cannot be found for Colombia, setting to 0", e);
        logger.error("Species count cannot be found for Colombia, setting to 0", e);
        contentView.addObject("totalOcurrenceRecordsCO", 0);
        contentView.addObject("speciesCountryCO", 0);
    }
}

From source file:org.gbif.portal.web.content.taxonomy.ClassificationFilterHelper.java

/**
 * @see org.gbif.portal.web.content.filter.FilterHelper#preProcess(java.util.List, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from ww  w  .  j  a  v  a2 s.  c om*/
public void preProcess(List<PropertyStoreTripletDTO> triplets, HttpServletRequest request,
        HttpServletResponse response) {

    //remove classification triplets, track them in list
    List<PropertyStoreTripletDTO> classificationTriplets = new ArrayList<PropertyStoreTripletDTO>();
    for (PropertyStoreTripletDTO triplet : triplets) {
        if (subject.equals(triplet.getSubject())) {
            classificationTriplets.add(triplet);
        }
    }
    triplets.removeAll(classificationTriplets);

    Locale locale = RequestContextUtils.getLocale(request);

    //change into a rank filter
    for (PropertyStoreTripletDTO triplet : classificationTriplets) {
        if (subject.equals(triplet.getSubject())) {
            try {
                String conceptKey = (String) triplet.getObject();
                TaxonConceptDTO taxonConcept = taxonomyManager.getTaxonConceptFor(conceptKey);
                if (taxonConcept == null) {
                    logger.error("Bad concept key: " + conceptKey);
                    return;
                }

                if (TaxonRankType.isRecognisedMajorRank(taxonConcept.getRank())) {
                    String acceptedConceptKey = null;
                    try {
                        acceptedConceptKey = (String) BeanUtils.getProperty(taxonConcept,
                                taxonConcept.getRank() + "ConceptKey");
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }

                    //check concept is accepted
                    if (addWarnings && conceptKey != null && acceptedConceptKey != null
                            && !conceptKey.equals(acceptedConceptKey)) {
                        conceptKey = acceptedConceptKey;
                        BriefTaxonConceptDTO briefAcceptedDTO = taxonomyManager
                                .getBriefTaxonConceptFor(acceptedConceptKey);
                        String[] objects = new String[3];
                        objects[0] = briefAcceptedDTO.getRank();
                        objects[1] = briefAcceptedDTO.getTaxonName();
                        objects[2] = taxonConcept.getTaxonName();
                        String warningMessage = messageSource.getMessage(acceptedConceptWarning, objects,
                                locale);
                        FilterUtils.addFilterWarning(request, warningMessage);
                    } else if (addWarnings && conceptKey != null) {
                        //check for synonyms and add warning if necessary
                        taxonConceptUtils.addSynonymWarnings(request, locale, taxonConcept);
                    }
                }

                if (taxonConcept == null)
                    triplet.setSubject(kingdomSubject);
                else if (taxonConcept.getRank().equals(TaxonRankType.KINGDOM_STR))
                    triplet.setSubject(kingdomSubject);
                else if (taxonConcept.getRank().equals(TaxonRankType.PHYLUM_STR))
                    triplet.setSubject(phylumSubject);
                else if (taxonConcept.getRank().equals(TaxonRankType.CLASS_STR))
                    triplet.setSubject(classSubject);
                else if (taxonConcept.getRank().equals(TaxonRankType.ORDER_STR))
                    triplet.setSubject(orderSubject);
                else if (taxonConcept.getRank().equals(TaxonRankType.FAMILY_STR))
                    triplet.setSubject(familySubject);
                else if (taxonConcept.getRank().equals(TaxonRankType.GENUS_STR))
                    triplet.setSubject(genusSubject);
                else if (taxonConcept.getRank().equals(TaxonRankType.SPECIES_STR))
                    triplet.setSubject(speciesSubject);
                else
                    triplet.setSubject(nubSubject);
                triplet.setObject(new Long(conceptKey));
                triplets.add(triplet);
            } catch (ServiceException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

From source file:org.gbif.portal.web.content.taxonomy.ScientificNameFilterHelper.java

/**
 * @see org.gbif.portal.web.content.filter.FilterHelper#preProcess(java.util.List, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*  ww w  .j  a  va 2 s  .com*/
public void preProcess(List<PropertyStoreTripletDTO> triplets, HttpServletRequest request,
        HttpServletResponse response) {

    List<PropertyStoreTripletDTO> scientificNameTriplets = new ArrayList<PropertyStoreTripletDTO>();
    for (PropertyStoreTripletDTO triplet : triplets) {
        if (triplet.getSubject().equals(subject)) {
            scientificNameTriplets.add(triplet);
        }
    }

    List<String> warnings = FilterUtils.getFilterWarnings(request);
    List<String> fatalWarnings = FilterUtils.getFatalFilterWarnings(request);

    try {
        //only search nub
        DataProviderDTO dp = dataResourceManager.getNubDataProvider();
        Locale locale = RequestContextUtils.getLocale(request);

        for (PropertyStoreTripletDTO scientificNameTriplet : scientificNameTriplets) {

            String scientificName = (String) scientificNameTriplet.getObject();
            //if it doesnt have wildcards
            if (!queryHelper.hasWildcards(scientificName)) {

                List<BriefTaxonConceptDTO> concepts = taxonConceptUtils.getTaxonConceptForSciName(
                        scientificName, dp.getKey(), null, allowUnconfirmedNames, maxConceptsToMatch, warnings,
                        fatalWarnings, locale);

                if (concepts != null && !concepts.isEmpty()) {

                    //remove the sci name triplet, as we have matches
                    triplets.remove(scientificNameTriplet);

                    for (BriefTaxonConceptDTO concept : concepts) {
                        //note we only support mapping of major ranks
                        String tripletSubject = rankToTripletSubjectMappings.get(concept.getRank());

                        if (tripletSubject != null) {
                            PropertyStoreTripletDTO psDTO = new PropertyStoreTripletDTO(
                                    scientificNameTriplet.getNamespace(), tripletSubject, equalsPredicate,
                                    new Long(concept.getKey()));
                            if (logger.isDebugEnabled()) {
                                logger.debug("Adding triplet: " + psDTO);
                            }
                            triplets.add(psDTO);

                            //if the taxon is not from nub provider, search for its speciesConceptKey also
                            //(i.e.: search for Felis concolor returns records for Felis concolor and Puma Concolor
                            if (concept.getSpeciesConceptKey() != null
                                    && !concept.getKey().equals(concept.getSpeciesConceptKey())) {
                                PropertyStoreTripletDTO psDTO2 = new PropertyStoreTripletDTO(
                                        scientificNameTriplet.getNamespace(), tripletSubject, equalsPredicate,
                                        new Long(concept.getSpeciesConceptKey()));
                                triplets.add(psDTO2);
                            }
                        }
                    }
                }
            }
        }

    } catch (ServiceException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.gbif.portal.web.controller.dataset.DataProviderLogController.java

/**
 * Adds the drop down content.//from  w ww.  j  a v  a2  s  .co m
 * @param request
 * @param mav
 */
@SuppressWarnings("unchecked")
private void addDropDownContent(HttpServletRequest request, ModelAndView mav) {

    //add today and a year from today
    Date today = new Date(System.currentTimeMillis());
    mav.addObject("today", today);
    Date lastWeek = DateUtils.addDays(today, -6);
    mav.addObject("lastWeek", lastWeek);
    Date oneMonthAgo = DateUtils.addMonths(today, -1);
    mav.addObject("oneMonthAgo", oneMonthAgo);
    Date oneYearAgo = DateUtils.addYears(today, -1);
    mav.addObject("oneYearAgo", oneYearAgo);

    //add event enumerations
    Collection<LogEvent> logEvents = (Collection) LogEvent.getValueMap().values();
    //split into 4 categories - Harvest, Extract, User and Other
    List<KeyValueDTO> harvestEvents = new ArrayList<KeyValueDTO>();
    List<KeyValueDTO> extractEvents = new ArrayList<KeyValueDTO>();
    List<KeyValueDTO> userEvents = new ArrayList<KeyValueDTO>();
    List<KeyValueDTO> usageEvents = new ArrayList<KeyValueDTO>();
    List<KeyValueDTO> otherEvents = new ArrayList<KeyValueDTO>();

    Locale locale = RequestContextUtils.getLocale(request);

    for (LogEvent logEvent : logEvents) {
        String name = messageSource.getMessage(logEvent.getName(), null, logEvent.getName(), locale);
        KeyValueDTO keyValue = new KeyValueDTO(logEvent.getValue().toString(), name);
        if (logEvent.getValue() >= LogEvent.HARVEST_RANGE_START
                && logEvent.getValue() <= LogEvent.HARVEST_RANGE_END)
            harvestEvents.add(keyValue);
        else if (logEvent.getValue() >= LogEvent.EXTRACT_RANGE_START
                && logEvent.getValue() <= LogEvent.EXTRACT_RANGE_END)
            extractEvents.add(keyValue);
        else if (logEvent.getValue() >= LogEvent.USER_RANGE_START
                && logEvent.getValue() <= LogEvent.USER_RANGE_END)
            userEvents.add(keyValue);
        else if (logEvent.getValue() >= LogEvent.USAGE_RANGE_START
                && logEvent.getValue() <= LogEvent.USAGE_RANGE_END)
            usageEvents.add(keyValue);
        else
            otherEvents.add(keyValue);
    }

    //sort alphabetically
    Collections.sort(harvestEvents, new KeyValueDTO.ValueComparator());
    Collections.sort(extractEvents, new KeyValueDTO.ValueComparator());
    Collections.sort(userEvents, new KeyValueDTO.ValueComparator());
    Collections.sort(otherEvents, new KeyValueDTO.ValueComparator());

    if (!harvestEvents.isEmpty() && harvestEvents.size() > 1) {
        harvestEvents.add(0, new KeyValueDTO(allHarvestEventsRequestKey,
                messageSource.getMessage("harvestAll", null, "Harvest - all", locale)));
    }
    mav.addObject("harvestEvents", harvestEvents);

    if (!extractEvents.isEmpty() && extractEvents.size() > 1) {
        extractEvents.add(0, new KeyValueDTO(allExtractEventsRequestKey,
                messageSource.getMessage("extractAll", null, "Extract - all", locale)));
        extractEvents.add(1, new KeyValueDTO(allExtractIssuesEventsRequestKey,
                messageSource.getMessage("extractAllIssues", null, "Extract - all issues", locale)));
    }
    mav.addObject("extractEvents", extractEvents);

    if (!userEvents.isEmpty() && userEvents.size() > 1) {
        userEvents.add(0, new KeyValueDTO(allUserEventsRequestKey,
                messageSource.getMessage("userAll", null, "User - all", locale)));
    }
    mav.addObject("userEvents", userEvents);

    if (!usageEvents.isEmpty() && usageEvents.size() > 1) {
        usageEvents.add(0, new KeyValueDTO(allUsageEventsRequestKey,
                messageSource.getMessage("usageAll", null, "Usage - all", locale)));
    }
    mav.addObject("usageEvents", usageEvents);
    mav.addObject("otherEvents", otherEvents);
}

From source file:org.gbif.portal.web.controller.filter.FilterDownloadController.java

/**
 * @see org.gbif.portal.web.controller.RestController#handleRequest(java.util.Map,
 *      javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//* w ww . j a v  a  2  s. c  om*/
@Override
public ModelAndView handleRequest(Map<String, String> propertiesMap, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // retrieve the request record total
    int recordCount = ServletRequestUtils.getIntParameter(request, recordCountRequestKey, maxResultsDownload);
    int maxDownloadOverrideRequestKey = ServletRequestUtils.getIntParameter(request,
            this.maxDownloadOverrideRequestKey, -1);
    if (recordCount > maxResultsDownload) {
        recordCount = maxResultsDownload;
    }
    if (maxDownloadOverrideRequestKey != -1) {
        recordCount = maxDownloadOverrideRequestKey;
    }

    // retrieve the supplied format
    String format = request.getParameter(formatRequestKey);

    // unravel the criteria
    Locale locale = RequestContextUtils.getLocale(request);
    String criteriaString = request.getParameter(criteriaRequestKey);
    logger.debug("criteriaString: " + criteriaString);
    CriteriaDTO criteria = CriteriaUtil.getCriteria(criteriaString, filters.getFilters(), locale);
    // fix criteria value
    CriteriaUtil.fixEncoding(request, criteria);
    List<PropertyStoreTripletDTO> triplets = queryHelper.getTriplets(filters.getFilters(), criteria, request,
            response);

    // retrieve the download field mappings
    Map<String, OutputProperty> downloadFieldMappings = (Map<String, OutputProperty>) propertyStore
            .getProperty(namespace, downloadFieldPSKey);

    // create the output process
    TripletQuery outputProcess = new TripletQuery();
    outputProcess.setTriplets(triplets);
    outputProcess.setMatchAll(matchAll);
    outputProcess.setSearchConstraints(new SearchConstraints(0, recordCount));
    TripletQueryManager tqm = format2TripletQueryManager.get(format);
    outputProcess.setTripletQueryManager(tqm);

    // retrieve the query description
    String queryDescription = FilterUtils.getQueryDescription(filters.getFilters(), criteria, messageSource,
            locale);

    // create a list of the requested fields
    List<Field> requestedFields = new ArrayList<Field>();

    if (request.getParameter(allFieldsRequestKey) != null) {
        logger.debug("All fields requested..");
        requestedFields.addAll(downloadFields);
        logger.debug("Requested fields: " + requestedFields.toString());
    } else {
        for (Field field : downloadFields) {
            if (request.getParameter(field.getFieldName()) != null)
                requestedFields.add(field);
        }
    }

    // get the file writer for the chosen format
    FileWriterFactory fwFactory = format2FileWriterFactories.get(format);
    if (fwFactory == null)
        return redirectToDefaultView();

    // search id
    String searchId = request.getParameter(searchIdRequestKey);
    String downloadFile = DownloadUtils.startFileWriter(request, response, requestedFields,
            downloadFieldMappings, outputProcess, null, queryDescription, fwFactory, downloadFilenamePrefix,
            searchId, zipped);

    String filenameWithExt = FilenameUtils.removeExtension(downloadFile);

    String criteriaUrl = CriteriaUtil.getUrl(criteria);
    String originalUrl = searchUrl + criteriaUrl;

    DownloadUtils.writeDownloadToDescriptor(request, filenameWithExt, originalUrl, downloadFileType,
            queryDescription, displayTimeTaken, null);
    // redirect to download preparing page
    ModelAndView mav = new ModelAndView(
            new RedirectView("/download/preparingDownload.htm?downloadFile=" + downloadFile, true));
    return mav;
}

From source file:org.gbif.portal.web.controller.geography.GeographyController.java

/**
 * @see org.gbif.portal.web.controller.RestController#handleRequest(java.util.List, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from w w  w.j  ava2  s  . c  o  m*/
@Override
public ModelAndView handleRequest(Map<String, String> properties, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String countryKey = properties.get(keyRequestKey);
    if (StringUtils.isNotEmpty(countryKey)) {
        CountryDTO country = null;
        Locale locale = RequestContextUtils.getLocale(request);
        if (geospatialManager.isValidISOCountryCode(countryKey)) {
            country = geospatialManager.getCountryForIsoCountryCode(countryKey, locale);
        } else if (geospatialManager.isValidCountryKey(countryKey)) {
            country = geospatialManager.getCountryFor(countryKey, locale);
        } else {
            SearchResultsDTO searchResultsDTO = geospatialManager.findCountries(countryKey, false, false, true,
                    locale, new SearchConstraints(0, 1));
            List results = searchResultsDTO.getResults();
            if (results != null && results.size() == 1)
                country = (CountryDTO) results.get(0);
        }

        if (country != null) {
            //sort counts into descending order
            List<CountDTO> resourceCounts = geospatialManager
                    .getDataResourceCountsForCountry(country.getIsoCountryCode(), true);
            List<CountDTO> countryCounts = geospatialManager
                    .getCountryCountsForCountry(country.getIsoCountryCode(), true, locale);
            List<CountDTO> nonCountryCounts = geospatialManager
                    .getCountryCountsForCountry(country.getIsoCountryCode(), false, locale);
            List<CountDTO> nonResourceCounts = geospatialManager
                    .getDataResourceCountsForCountry(country.getIsoCountryCode(), false);
            geospatialManager.synchronizeLists(resourceCounts, nonResourceCounts);
            geospatialManager.synchronizeLists(countryCounts, nonCountryCounts);
            if (sortResourcesByCount) {
                Collections.sort(resourceCounts, new Comparator<CountDTO>() {
                    public int compare(CountDTO o1, CountDTO o2) {
                        if (o1 == null || o2 == null || o1.getCount() == null || o2.getCount() == null)
                            return -1;
                        return o1.getCount().compareTo(o2.getCount()) * -1;
                    }
                });
                Collections.sort(nonResourceCounts, new Comparator<CountDTO>() {
                    public int compare(CountDTO o1, CountDTO o2) {
                        if (o1 == null || o2 == null || o1.getCount() == null || o2.getCount() == null)
                            return -1;
                        return o1.getCount().compareTo(o2.getCount()) * -1;
                    }
                });
            }

            boolean showHosted = ServletRequestUtils.getBooleanParameter(request, hostedModelKey, false);
            EntityType entityType = null;
            if (showHosted) {
                entityType = EntityType.TYPE_HOME_COUNTRY;
            } else {
                entityType = EntityType.TYPE_COUNTRY;
            }

            ModelAndView mav = resolveAndCreateView(properties, request, false);
            mav.addObject(countryModelKey, country);
            mav.addObject(resourceCountsModelKey, resourceCounts);
            mav.addObject(nonResourceCountsModelKey, nonResourceCounts);
            mav.addObject(countryCountsModelKey, countryCounts);
            mav.addObject(nonCountryCountsModelKey, nonCountryCounts);

            if (logger.isDebugEnabled())
                logger.debug("Returning details of:" + country);

            //if zoom level not specified, jump to correct zoom level for this country
            if (!MapContentProvider.zoomLevelSpecified(request) && !showHosted
                    && country.getMinLongitude() != null && country.getMinLatitude() != null
                    && country.getMaxLongitude() != null && country.getMaxLatitude() != null) {
                //zoom to the correct level for this country
                mapContentProvider.addMapContent(request, entityType.getName(), country.getKey(),
                        country.getMinLongitude(), country.getMinLatitude(), country.getMaxLongitude(),
                        country.getMaxLatitude());
                mapContentProvider.addPointsTotalsToRequest(request, entityType, country.getKey(),
                        new BoundingBoxDTO(country.getMinLongitude(), country.getMinLatitude(),
                                country.getMaxLongitude(), country.getMaxLatitude()));
            } else {
                //zoom to the level specified in the request         
                mapContentProvider.addMapContent(request, entityType.getName(), country.getKey());
                mapContentProvider.addPointsTotalsToRequest(request, entityType, country.getKey(), null);
            }
            return mav;
        }
    }
    return redirectToDefaultView();
}

From source file:org.gbif.portal.web.controller.occurrence.OccurrenceController.java

/**
   * Adds the parsed details for this record.
   * /*ww w .j  av a  2s .c  o m*/
   * @param request
   * @param mav
   * @param occurrenceRecord
   * @param rawOccurrenceRecord
   * @throws ServiceException
   */
  private void addParsedData(HttpServletRequest request, ModelAndView mav, OccurrenceRecordDTO occurrenceRecord,
          RawOccurrenceRecordDTO rawOccurrenceRecord) throws ServiceException {

      logger.debug("Adding parsed data");
      //TODO optimise for performance - reduce the number of selects      
      TaxonConceptDTO taxonConceptDTO = taxonomyManager.getTaxonConceptFor(occurrenceRecord.getTaxonConceptKey());
      if (taxonConceptDTO != null) {
          List<BriefTaxonConceptDTO> concepts = taxonomyManager.getClassificationFor(taxonConceptDTO.getKey(),
                  false, null, true);
          mav.addObject("concepts", concepts);
      }
      DataResourceDTO dataResource = dataResourceManager
              .getDataResourceFor(occurrenceRecord.getDataResourceKey());
      DataProviderDTO dataProvider = dataResourceManager.getDataProviderFor(dataResource.getDataProviderKey());
      Locale locale = RequestContextUtils.getLocale(request);
      CountryDTO country = geospatialManager.getCountryForIsoCountryCode(occurrenceRecord.getIsoCountryCode(),
              locale);
      mav.addObject("occurrenceRecord", occurrenceRecord);
      mav.addObject("taxonConcept", taxonConceptDTO);
      mav.addObject("dataResource", dataResource);
      mav.addObject("dataProvider", dataProvider);
      mav.addObject("country", country);
      mav.addObject(messageSourceKey, messageSource);
      mav.addObject("locale", locale);

      //add an image to this request - with image dimension for scaling
      logger.debug("Adding image records");
      List<ImageRecordDTO> imageRecords = occurrenceManager
              .getImageRecordsForOccurrenceRecord(occurrenceRecord.getKey());
      if (!imageRecords.isEmpty()) {
          mav.addObject("imageRecords", imageRecords);
      }

      //Typification details
      logger.debug("Adding typification records");
      List<TypificationRecordDTO> typifications = occurrenceManager
              .getTypificationRecordsForOccurrenceRecord(occurrenceRecord.getKey());
      mav.addObject("typifications", typifications);

      //link records
      logger.debug("Adding link records");
      List<LinkRecordDTO> linkRecords = occurrenceManager
              .getLinkRecordsForOccurrenceRecord(occurrenceRecord.getKey());
      mav.addObject("linkRecords", linkRecords);

      //identifier records         
      logger.debug("Adding identifier records");
      List<IdentifierRecordDTO> identifierRecords = occurrenceManager
              .getIdentifierRecordsForOccurrenceRecord(occurrenceRecord.getKey());
      mav.addObject("identifierRecords", identifierRecords);

      //include brief concepts for major ranks - needed for back links to nub
      if (StringUtils.isNotBlank(rawOccurrenceRecord.getKingdom())
              && taxonConceptDTO.getKingdomConceptKey() != null)
          mav.addObject("kingdomConcept",
                  taxonomyManager.getBriefTaxonConceptFor(taxonConceptDTO.getKingdomConceptKey()));

      if (StringUtils.isNotBlank(rawOccurrenceRecord.getPhylum())
              && taxonConceptDTO.getPhylumConceptKey() != null)
          mav.addObject("phylumConcept",
                  taxonomyManager.getBriefTaxonConceptFor(taxonConceptDTO.getPhylumConceptKey()));

      if (StringUtils.isNotBlank(rawOccurrenceRecord.getBioClass())
              && taxonConceptDTO.getClassConceptKey() != null)
          mav.addObject("classConcept",
                  taxonomyManager.getBriefTaxonConceptFor(taxonConceptDTO.getClassConceptKey()));

      if (StringUtils.isNotBlank(rawOccurrenceRecord.getOrder()) && taxonConceptDTO.getOrderConceptKey() != null)
          mav.addObject("orderConcept",
                  taxonomyManager.getBriefTaxonConceptFor(taxonConceptDTO.getOrderConceptKey()));

      if (StringUtils.isNotBlank(rawOccurrenceRecord.getFamily())
              && taxonConceptDTO.getFamilyConceptKey() != null)
          mav.addObject("familyConcept",
                  taxonomyManager.getBriefTaxonConceptFor(taxonConceptDTO.getFamilyConceptKey()));

      if (StringUtils.isNotBlank(rawOccurrenceRecord.getGenus()) && taxonConceptDTO.getGenusConceptKey() != null)
          mav.addObject("genusConcept",
                  taxonomyManager.getBriefTaxonConceptFor(taxonConceptDTO.getGenusConceptKey()));

      if (StringUtils.isNotBlank(rawOccurrenceRecord.getSpecies())
              && taxonConceptDTO.getSpeciesConceptKey() != null)
          mav.addObject("speciesConcept",
                  taxonomyManager.getBriefTaxonConceptFor(taxonConceptDTO.getSpeciesConceptKey()));

      if (StringUtils.isNotBlank(rawOccurrenceRecord.getSubspecies()))
          mav.addObject("subspeciesConcept", taxonConceptDTO);

      //add the nub concept if available   
      if (taxonConceptDTO.getPartnerConceptKey() != null) {
          logger.debug("Adding partner concept");
          TaxonConceptDTO partnerConcept = taxonomyManager
                  .getTaxonConceptFor(taxonConceptDTO.getPartnerConceptKey());
          mav.addObject("partnerConcept", partnerConcept);
      }

      //add one degree cell bounding box
      if (occurrenceRecord.getLatitude() != null && occurrenceRecord.getLongitude() != null) {
          logger.debug("Adding one degree cell bounding box");
          float latitude = occurrenceRecord.getLatitude();
          float longitude = occurrenceRecord.getLongitude();
          float minLong = longitude - (cellWidth / 2);
          float minLat = latitude - (cellWidth / 2);
          float maxLong = longitude + (cellWidth / 2);
          float maxLat = latitude + (cellWidth / 2);

          //sanity checks
          if (minLat < -90) {
              minLat = -90;
              maxLat = minLat + cellWidth;
          }
          if (maxLat > 90) {
              maxLat = 90;
              minLat = maxLat - cellWidth;
          }
          if (minLong < -180) {
              minLong = -180;
              maxLong = minLong + cellWidth;
          }
          if (maxLat > 90) {
              maxLat = 90;
              minLat = maxLat - cellWidth;
          }

          //for region link
          mav.addObject("minX", minLong);
          mav.addObject("minY", minLat);
          mav.addObject("maxX", maxLong);
          mav.addObject("maxY", maxLat);
      }
  }

From source file:org.gbif.portal.web.controller.occurrence.OccurrenceFilterController.java

/**
 * Performs the count triplet query and returns the generic count view for occurrences.
 * //w  w  w.j  av  a 2  s  . c  o  m
 * @param triplets
 * @return
 * @throws UnsupportedEncodingException
 */
@SuppressWarnings("unchecked")
private ModelAndView getCountryCountsView(HttpServletRequest request, HttpServletResponse response,
        String returnFieldsKey, String viewName, SearchConstraints searchConstraints)
        throws Exception, ServiceException, UnsupportedEncodingException {
    CriteriaDTO criteriaDTO = CriteriaUtil.getCriteria(request, occurrenceFilters.getFilters());
    // fix criteria value
    request.setCharacterEncoding("UTF-8");
    CriteriaUtil.fixEncoding(request, criteriaDTO);
    List<PropertyStoreTripletDTO> triplets = queryHelper.getTriplets(occurrenceFilters.getFilters(),
            criteriaDTO, request, response);
    triplets.add(new PropertyStoreTripletDTO(queryHelper.getQueryNamespace(), selectFieldSubject,
            returnPredicateSubject, returnFieldsKey));
    SearchResultsDTO searchResults = countsQueryManager.doTripletQuery(triplets, criteriaDTO.isMatchAll(),
            searchConstraints);

    List<CountDTO> countDTOs = searchResults.getResults();
    final Locale locale = RequestContextUtils.getLocale(request);

    Collections.sort(countDTOs, new Comparator() {

        public int compare(Object count1, Object count2) {
            CountDTO countDTO1 = (CountDTO) count1;
            CountDTO countDTO2 = (CountDTO) count2;

            CountryDTO countryDTO1 = geospatialManager.getCountryForIsoCountryCode(countDTO1.getKey(), locale);
            CountryDTO countryDTO2 = geospatialManager.getCountryForIsoCountryCode(countDTO2.getKey(), locale);

            if (countryDTO1 == null)
                return 1;
            if (countryDTO2 == null)
                return -1;

            return countryDTO1.getName().compareToIgnoreCase(countryDTO2.getName());
        }
    });

    ModelAndView mav = new ModelAndView(viewName);
    mav.addObject(countsModelKey, searchResults);
    mav.addObject(resultsModelKey, countDTOs);
    // add filters
    mav.addObject(filtersRequestKey, occurrenceFilters.getFilters());
    mav.addObject(criteriaRequestKey, criteriaDTO);
    return mav;
}

From source file:org.gbif.portal.web.controller.occurrence.OccurrenceFilterController.java

/**
 * Determines the view based on the map provided, and if none found defaults to the
 * "occurrenceFilter" view./*from ww  w . j ava  2s .  co m*/
 * 
 * @param request To get the view from
 * @param response To write to
 * @return The model and view for the filter params provided
 */
public ModelAndView search(HttpServletRequest request, HttpServletResponse response) throws Exception {

    // retrieve the criteria from the request
    CriteriaDTO criteria = CriteriaUtil.getCriteria(request, occurrenceFilters.getFilters());
    // fix criteria value
    CriteriaUtil.fixEncoding(request, criteria);

    logger.debug("Criteria list: " + criteria);

    // check for data provider ids
    String[] dataProviderIds = request.getParameterValues(dataProviderParameterKey);
    if (dataProviderIds != null && dataProviderIds.length > 0) {
        for (String dataProviderId : dataProviderIds) {
            CriterionDTO criterionDTO = new CriterionDTO(dataProviderIdFilter.getId(),
                    dataProviderIdFilter.getDefaultPredicateId(), dataProviderId);
            criteria.getCriteria().add(criterionDTO);
        }
    }
    // check for data resource ids
    String[] dataResourceIds = request.getParameterValues(dataResourceParameterKey);
    if (dataResourceIds != null && dataResourceIds.length > 0) {
        for (String dataResourceId : dataResourceIds) {
            CriterionDTO criterionDTO = new CriterionDTO(dataResourceIdFilter.getId(),
                    dataResourceIdFilter.getDefaultPredicateId(), dataResourceId);
            criteria.getCriteria().add(criterionDTO);
        }
    }
    // check for country ids
    String[] countryIds = request.getParameterValues(countryParameterKey);
    if (countryIds != null && countryIds.length > 0) {
        for (String countryId : countryIds) {
            CriterionDTO criterionDTO = new CriterionDTO(countryFilter.getId(),
                    countryFilter.getDefaultPredicateId(), countryId);
            criteria.getCriteria().add(criterionDTO);
        }
    }
    Locale locale = RequestContextUtils.getLocale(request);
    CriteriaUtil.populateCriteria(occurrenceFilters.getFilters(), criteria, locale);
    criteria.setCriteria(CriteriaUtil.removeDuplicates(criteria.getCriteria()));

    // convert to triplets
    List<PropertyStoreTripletDTO> triplets = queryHelper.getTriplets(occurrenceFilters.getFilters(), criteria,
            request, response);
    ModelAndView mav = new ModelAndView("occurrenceSearchWithEditorPane");

    // check for a set filter
    String subject = request.getParameter("newFilterSubject");
    String predicate = request.getParameter("newFilterPredicate");
    String value = request.getParameter("newFilterValue");
    value = QueryHelper.tidyValue(value);

    if (subject != null && predicate != null && value != null) {
        // initialise the filter
        CriterionDTO criterion = new CriterionDTO(subject, predicate, value);
        CriteriaUtil.setCriterionDisplayValue(occurrenceFilters.getFilters(), criterion, locale);
        mav.addObject(currentCriterionModelKey, criterion);
        FilterDTO filter = FilterUtils.getFilterById(occurrenceFilters.getFilters(), criterion.getSubject());
        if (filter.getFilterHelper() != null)
            filter.getFilterHelper().addCriterion2Request(criterion, mav, request);
    }

    // do the query
    if (FilterUtils.isFilterQueryRequestValid(request)) {
        SearchResultsDTO searchResults = tripletQueryManager.doTripletQuery(triplets, true,
                new SearchConstraints(0, maxSampleResults));
        mav.addObject(resultsModelKey, searchResults.getResults());
    }
    // construct the model
    boolean oneClassification = false;
    int classificationCount = 0;
    for (CriterionDTO criterion : criteria.getCriteria()) {
        logger.debug("criterion: " + criterion);
        // search request contains a classification filter
        if (criterion.getSubject().equals(classificationFilterValue)) {
            if (classificationCount < 1) {
                // check that classification contains a species level (or lower) taxon
                if (taxonomyManager.getBriefTaxonConceptFor(criterion.getValue()).getRankValue() >= 6000) {
                    logger.debug("Taxon included on the classification filter is species level or lower");
                    oneClassification = true;
                }
            }
            // there is more than one classification
            else {
                oneClassification = false;
                // no use to continue searching
                break;
            }
            classificationCount++;
        }
    }
    mav.addObject(oneClassificationKey, oneClassification);
    mav.addObject(criteriaRequestKey, criteria);
    mav.addObject(filtersRequestKey, occurrenceFilters.getFilters());
    mav.addObject(messageSourceKey, messageSource);
    mav.addObject(rootWizardUrlModelKey, rootWizardUrl);
    return mav;
}

From source file:org.gbif.portal.web.controller.occurrence.OccurrenceFilterController.java

/**
 * Retrieves the counts against the countries for this set of criteria
 * /*from  w  w  w  . j av  a2 s  .c o  m*/
 * @param request
 * @param response
 * @return ModelAndView which contains the provider list and counts
 * @throws UnsupportedEncodingException
 */
public ModelAndView searchCountries(HttpServletRequest request, HttpServletResponse response)
        throws Exception, ServiceException, UnsupportedEncodingException {
    // interrogate the criteria - if it only contains a taxon filter then switch
    CriteriaDTO criteriaDTO = CriteriaUtil.getCriteria(request, occurrenceFilters.getFilters());
    // fix criteria value
    request.setCharacterEncoding("ISO-8859-1");
    CriteriaUtil.fixEncoding(request, criteriaDTO);
    if (criteriaDTO.size() == 1) {
        logger.debug("Switching to using service layer method getCountryCountsForTaxonConcept");
        CriterionDTO criterionDTO = criteriaDTO.get(0);
        FilterDTO filterDTO = FilterUtils.getFilterById(occurrenceFilters.getFilters(),
                criterionDTO.getSubject());
        if (filterDTO.getSubject().equals(classificationFilter.getSubject())) {
            List<CountDTO> counts = taxonomyManager.getCountryCountsForTaxonConcept(criterionDTO.getValue(),
                    RequestContextUtils.getLocale(request));
            ModelAndView mav = new ModelAndView(occurrenceFilterCountryCountsView);
            mav.addObject(countsModelKey, counts);
            mav.addObject(resultsModelKey, counts);
            // add filters
            mav.addObject(filtersRequestKey, occurrenceFilters.getFilters());
            mav.addObject(criteriaRequestKey, criteriaDTO);
            mav.addObject(countsAvailableModelKey, true);
            return mav;
        }
    }
    int totalNoOfCountries = geospatialManager.getTotalCountryCount();
    return getCountryCountsView(request, response, "SERVICE.OCCURRENCE.QUERY.RETURNFIELDS.COUNTRYCOUNTS",
            occurrenceFilterCountryCountsView, new SearchConstraints(0, totalNoOfCountries));
}