Search in sources :

Example 11 with Filter

use of org.hippoecm.hst.content.beans.query.filter.Filter in project hippo by NHS-digital-website.

the class CyberAlertResource method fetchCyberAlert.

@GET
@Path("/single/")
public CyberAlert fetchCyberAlert(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse, @Context UriInfo uriInfo, @PathParam("threatid") String threatid) {
    CyberAlert cyberAlert = null;
    try {
        threatid = servletRequest.getParameter("threatid");
        if (threatid != null) {
            HstRequestContext requestContext = RequestContextProvider.get();
            HstQueryManager hstQueryManager = getHstQueryManager(requestContext.getSession(), requestContext);
            String mountContentPath = requestContext.getResolvedMount().getMount().getContentPath();
            Node mountContentNode = requestContext.getSession().getRootNode().getNode(PathUtils.normalizePath(mountContentPath));
            HstQuery hstQuery = hstQueryManager.createQuery(mountContentNode, CyberAlert.class);
            Filter filter = hstQuery.createFilter();
            filter.addEqualTo("website:threatid", threatid);
            hstQuery.setFilter(filter);
            hstQuery.setLimit(1);
            HstQueryResult result = hstQuery.execute();
            HippoBeanIterator iterator = result.getHippoBeans();
            if (iterator.hasNext()) {
                cyberAlert = (CyberAlert) iterator.nextHippoBean();
            } else {
                JSONObject json = new JSONObject();
                json.put("error", "The threatid=" + threatid + " is not found");
                servletResponse.resetBuffer();
                servletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
                servletResponse.setHeader("Content-Type", "application/json");
                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.getWriter().write(json.toString());
                servletResponse.flushBuffer();
            }
        } else {
            JSONObject json = new JSONObject();
            json.put("error", "The URL is not correct. Use /single?threatid=<threatid>");
            servletResponse.resetBuffer();
            servletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
            servletResponse.setHeader("Content-Type", "application/json");
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.getWriter().write(json.toString());
            servletResponse.flushBuffer();
        }
    } catch (Exception queryException) {
        log.warn("QueryException ", queryException);
    }
    return cyberAlert;
}
Also used : HstQuery(org.hippoecm.hst.content.beans.query.HstQuery) JSONObject(org.json.simple.JSONObject) Filter(org.hippoecm.hst.content.beans.query.filter.Filter) HippoBeanIterator(org.hippoecm.hst.content.beans.standard.HippoBeanIterator) Node(javax.jcr.Node) HstQueryManager(org.hippoecm.hst.content.beans.query.HstQueryManager) CyberAlert(uk.nhs.digital.website.beans.CyberAlert) HstRequestContext(org.hippoecm.hst.core.request.HstRequestContext) HstQueryResult(org.hippoecm.hst.content.beans.query.HstQueryResult) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 12 with Filter

use of org.hippoecm.hst.content.beans.query.filter.Filter in project hippo by NHS-digital-website.

the class CommonFieldsBean method getNews.

private List<News> getNews(boolean isLatestNews) throws HstComponentException, QueryException {
    List<String> linkPaths = new ArrayList<>();
    linkPaths.add("website:relateddocuments/@hippo:docbase");
    linkPaths.add("website:peoplementioned/@hippo:docbase");
    Filter filter = getInitialQuery(linkPaths, News.class).createFilter();
    Calendar thresholdDate = Calendar.getInstance();
    thresholdDate.add(Calendar.MONTH, -2);
    if (isLatestNews) {
        filter.addGreaterOrEqualThan("website:publisheddatetime", thresholdDate, DateTools.Resolution.DAY);
    } else {
        filter.addLessThan("website:publisheddatetime", thresholdDate, DateTools.Resolution.DAY);
    }
    List<BaseFilter> filters = new ArrayList<BaseFilter>();
    filters.add(filter);
    // originally based on DW-1105 acceptance criteria - changed to fit DW-2238
    int maxElements = 7;
    return getRelatedDocuments(linkPaths, maxElements, null, null, News.class, filters);
}
Also used : Filter(org.hippoecm.hst.content.beans.query.filter.Filter) BaseFilter(org.hippoecm.hst.content.beans.query.filter.BaseFilter) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) BaseFilter(org.hippoecm.hst.content.beans.query.filter.BaseFilter)

Example 13 with Filter

use of org.hippoecm.hst.content.beans.query.filter.Filter in project hippo by NHS-digital-website.

the class FeedListComponent method contributeAndFilters.

@Override
protected void contributeAndFilters(final List<BaseFilter> filters, final HstRequest request, final HstQuery query) {
    FeedListComponentInfo info = getComponentParametersInfo(request);
    // Filter for News
    if (info.getDocumentTypes().equals("website:news")) {
        if (info.getHideFutureItems()) {
            final String documentDateField = info.getDocumentDateField();
            if (!Strings.isNullOrEmpty(documentDateField)) {
                try {
                    Filter filter = query.createFilter();
                    filter.addLessOrEqualThan(documentDateField, Calendar.getInstance(), DateTools.Resolution.DAY);
                    filters.add(filter);
                } catch (FilterException e) {
                    log.error("An exception occurred while trying to create a query filter for hiding future items: {}", e, e);
                }
            }
        }
        query.addOrderByDescending("website:publisheddatetime");
        // filtering on 'Display on news hub and homepage' property, if it has been selected
        try {
            Filter filter = query.createFilter();
            filter.addEqualTo("website:display", true);
            filters.add(filter);
        } catch (FilterException var7) {
            // Exception is entered twice - once as a parameter for the string, and once as the actual exception thrown
            // see: http://www.slf4j.org/faq.html#paramException
            log.error("An exception occurred while trying to create a query filter showing document with display field on : {}", var7, var7);
        }
    }
    // Filter for Blogs
    if (info.getDocumentTypes().equals("website:blog")) {
        query.addOrderByDescending("website:dateofpublication");
    }
    // Filter for Events
    if (info.getDocumentTypes().equals("website:event")) {
        // filter's documents such that the website:display is set to true
        try {
            Filter filter = query.createFilter();
            filter.addEqualTo("website:display", true);
            filters.add(filter);
        } catch (FilterException var7) {
            log.error("An exception occurred while trying to create a query filter showing document with display field on : {}", var7, var7);
        }
        // fetching the selected types from the request
        String[] selectedTypes = getSelectedTypes(request);
        if (selectedTypes.length > 0) {
            final Filter filter = query.createFilter();
            for (String type : selectedTypes) {
                try {
                    filter.addEqualTo("@website:type", type);
                } catch (FilterException filterException) {
                    log.warn("Errors while adding event type filter {}", filterException, filterException);
                }
            }
            filters.add(filter);
        }
    }
}
Also used : BaseFilter(org.hippoecm.hst.content.beans.query.filter.BaseFilter) Filter(org.hippoecm.hst.content.beans.query.filter.Filter) FilterException(org.hippoecm.hst.content.beans.query.exceptions.FilterException) FeedListComponentInfo(uk.nhs.digital.common.components.info.FeedListComponentInfo)

Example 14 with Filter

use of org.hippoecm.hst.content.beans.query.filter.Filter in project hippo by NHS-digital-website.

the class FeedListComponent method addIntervalConstraint.

/**
 * Copied from uk.nhs.digital.common.components.EventsComponent
 */
protected void addIntervalConstraint(final List filters, final HstQuery hstQuery, final String dateField, final HstRequest request) throws FilterException {
    Calendar calendar = Calendar.getInstance();
    int year = Integer.parseInt(DocumentUtils.findYearOrDefault(getSelectedYear(request), calendar.get(Calendar.YEAR)));
    final Filter filter = hstQuery.createFilter();
    calendar.set(Calendar.YEAR, year);
    filter.addBetween(dateField, calendar, calendar, DateTools.Resolution.YEAR);
    filters.add(filter);
}
Also used : BaseFilter(org.hippoecm.hst.content.beans.query.filter.BaseFilter) Filter(org.hippoecm.hst.content.beans.query.filter.Filter)

Example 15 with Filter

use of org.hippoecm.hst.content.beans.query.filter.Filter in project hippo by NHS-digital-website.

the class FeedListComponent method addIntervalFilter.

/**
 * This method is creating an xpath query that will be appended to the query produced by the EssentialListComponent.
 * The main goal of this component is to query the interval compound and NOT the event documents: for this reason
 * we need to customize the query manually to have this behavior
 * <p>
 * Copied from uk.nhs.digital.common.components.EventsComponent
 *
 * @param request needed to build the new query
 * @return String containing the query for the interval compound
 */
protected String addIntervalFilter(final HstRequest request) {
    final FeedListComponentInfo paramInfo = getComponentParametersInfo(request);
    final String dateField = paramInfo.getDocumentDateField();
    if (!Strings.isNullOrEmpty(dateField)) {
        // filter list containing dates contraints
        try {
            HstQueryBuilder hstQueryBuider = HstQueryBuilder.create(request.getRequestContext().getSiteContentBaseBean());
            hstQueryBuider.ofTypes("website:interval");
            HstQuery hstQuery = hstQueryBuider.build();
            List<BaseFilter> filters = new ArrayList<>();
            // adding the interval date range constraint
            addIntervalConstraint(filters, hstQuery, dateField, request);
            if (paramInfo.getHidePastEvents()) {
                try {
                    final Filter filter = hstQuery.createFilter();
                    filter.addGreaterOrEqualThan(dateField, Calendar.getInstance(), DateTools.Resolution.DAY);
                    filters.add(filter);
                } catch (FilterException e) {
                    log.error("Error while creating query filter to hide past events using date field {}", dateField, e);
                }
            }
            final Filter queryFilter = createQueryFilter(request, hstQuery);
            if (queryFilter != null) {
                filters.add(queryFilter);
            }
            // appling the filters on the hstQuery object
            applyAndFilters(hstQuery, filters);
            // Apply sort
            if (paramInfo.getHidePastEvents()) {
                hstQuery.addOrderByAscending(dateField);
            } else {
                // past events sorted descending order by date, most recent first
                hstQuery.addOrderByDescending(dateField);
            }
            // removing existing filters the query, since it shouldn't include path, availability and query constraint
            String intervalQueryString = hstQuery.getQueryAsString(true).replaceAll("\\(@hippo:paths='[^']*'\\)( and)?", "");
            intervalQueryString = intervalQueryString.replaceAll("\\(@hippo:availability='[^']*'\\)( and)?", "");
            intervalQueryString = intervalQueryString.replaceAll("not\\(@jcr:primaryType='nt:frozenNode'\\)( and)?", "");
            // removing the first slash, since the string must be appended to an existing xpath query
            return intervalQueryString.substring(1, intervalQueryString.length());
        } catch (FilterException filterException) {
            log.warn("Exceptions while adding event date range filter {} ", filterException, filterException);
        } catch (QueryException queryException) {
            log.warn("Exceptions while getting the string representation of the query {} ", queryException, queryException);
        }
    }
    return "";
}
Also used : HstQuery(org.hippoecm.hst.content.beans.query.HstQuery) QueryException(org.hippoecm.hst.content.beans.query.exceptions.QueryException) HstQueryBuilder(org.hippoecm.hst.content.beans.query.builder.HstQueryBuilder) BaseFilter(org.hippoecm.hst.content.beans.query.filter.BaseFilter) Filter(org.hippoecm.hst.content.beans.query.filter.Filter) FilterException(org.hippoecm.hst.content.beans.query.exceptions.FilterException) FeedListComponentInfo(uk.nhs.digital.common.components.info.FeedListComponentInfo) BaseFilter(org.hippoecm.hst.content.beans.query.filter.BaseFilter)

Aggregations

Filter (org.hippoecm.hst.content.beans.query.filter.Filter)17 BaseFilter (org.hippoecm.hst.content.beans.query.filter.BaseFilter)15 FilterException (org.hippoecm.hst.content.beans.query.exceptions.FilterException)8 HstQuery (org.hippoecm.hst.content.beans.query.HstQuery)4 QueryException (org.hippoecm.hst.content.beans.query.exceptions.QueryException)4 ArrayList (java.util.ArrayList)2 Calendar (java.util.Calendar)2 HstQueryBuilder (org.hippoecm.hst.content.beans.query.builder.HstQueryBuilder)2 HippoBeanIterator (org.hippoecm.hst.content.beans.standard.HippoBeanIterator)2 HstRequestContext (org.hippoecm.hst.core.request.HstRequestContext)2 FeedListComponentInfo (uk.nhs.digital.common.components.info.FeedListComponentInfo)2 Month (java.time.Month)1 Node (javax.jcr.Node)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 HstQueryManager (org.hippoecm.hst.content.beans.query.HstQueryManager)1 HstQueryResult (org.hippoecm.hst.content.beans.query.HstQueryResult)1 HippoDocument (org.hippoecm.hst.content.beans.standard.HippoDocument)1 JSONObject (org.json.simple.JSONObject)1 EssentialsEventsComponentInfo (org.onehippo.cms7.essentials.components.info.EssentialsEventsComponentInfo)1