podd.search.web.SearchCriteriaWeb.java Source code

Java tutorial

Introduction

Here is the source code for podd.search.web.SearchCriteriaWeb.java

Source

/*
 * Copyright (c) 2009 - 2010. School of Information Technology and Electrical
 * Engineering, The University of Queensland.  This software is being developed
 * for the "Phenomics Ontoogy Driven Data Management Project (PODD)" project.
 * PODD is a National e-Research Architecture Taskforce (NeAT) project
 * co-funded by ANDS and ARCS.
 *
 * PODD is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PODD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PODD.  If not, see <http://www.gnu.org/licenses/>.
 */

package podd.search.web;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import podd.dataaccess.service.ProjectService;
import podd.model.project.Project;
import podd.model.project.Project.ProjectPublicationStatus;
import podd.model.project.ProjectStatus;
import podd.model.user.User;
import podd.model.user.search.UserSearchCriteria;
import podd.model.user.search.impl.UserSearchCriteriaImpl;
import podd.search.SearchCriteria;
import podd.search.impl.SearchCriteriaImpl;

/**
 * A Search Criteria Application service for capturing input fields from the web
 * @author Philip Wu
 *
 */
public class SearchCriteriaWeb {

    static final Logger LOGGER = Logger.getLogger(SearchCriteriaWeb.class);

    public static final String URL_ENCODING = "UTF-8";

    // Current authenticated User if any
    protected User authenticatedUser;

    // Queries
    protected String queryAllTheseWords;
    protected String queryAnyTheseWords;
    protected String queryPhrase;
    protected String queryExclude;

    //Filters
    protected String startCreationDate;
    protected String endCreationDate;
    protected List<String> objectTypes;

    // Scope
    protected String strScopeMyProjects;
    protected String strScopePublicProjects;

    // project statuses
    protected String projectStatus;
    protected String publicationStatus;

    protected Long start;

    /**
     * Provide access to all the projects associated with a particular user
     */
    protected ProjectService projectService;

    public SearchCriteriaWeb(ProjectService projectService) {
        this.projectService = projectService;
    }

    public User getAuthenticatedUser() {
        return authenticatedUser;
    }

    public SearchCriteriaWeb setAuthenticatedUser(User authenticatedUser) {
        this.authenticatedUser = authenticatedUser;
        return this;
    }

    public String getQueryAllTheseWords() {
        return queryAllTheseWords;
    }

    public SearchCriteriaWeb setQueryAllTheseWords(String queryAllTheseWords) {
        this.queryAllTheseWords = queryAllTheseWords;
        return this;
    }

    public String getQueryAnyTheseWords() {
        return queryAnyTheseWords;
    }

    public SearchCriteriaWeb setQueryAnyTheseWords(String queryAnyTheseWords) {
        this.queryAnyTheseWords = queryAnyTheseWords;
        return this;
    }

    public String getQueryPhrase() {
        return queryPhrase;
    }

    public SearchCriteriaWeb setQueryPhrase(String queryPhrase) {
        this.queryPhrase = queryPhrase;
        return this;
    }

    public String getQueryExclude() {
        return queryExclude;
    }

    public SearchCriteriaWeb setQueryExclude(String queryExclude) {
        this.queryExclude = queryExclude;
        return this;
    }

    public String getStartCreationDate() {
        return startCreationDate;
    }

    public SearchCriteriaWeb setStartCreationDate(String startCreationDate) {
        this.startCreationDate = startCreationDate;
        return this;
    }

    public String getEndCreationDate() {
        return endCreationDate;
    }

    public SearchCriteriaWeb setEndCreationDate(String endCreationDate) {
        this.endCreationDate = endCreationDate;
        return this;
    }

    public List<String> getObjectTypes() {
        return objectTypes;
    }

    public SearchCriteriaWeb setObjectTypes(List<String> objectTypes) {
        this.objectTypes = objectTypes;
        return this;
    }

    public String getStrScopeMyProjects() {
        return strScopeMyProjects;
    }

    public SearchCriteriaWeb setStrScopeMyProjects(String strScopeMyProjects) {
        this.strScopeMyProjects = strScopeMyProjects;
        return this;
    }

    public String getStrScopePublicProjects() {
        return strScopePublicProjects;
    }

    public SearchCriteriaWeb setStrScopePublicProjects(String strScopePublicProjects) {
        this.strScopePublicProjects = strScopePublicProjects;
        return this;
    }

    public String getProjectStatus() {
        return projectStatus;
    }

    public SearchCriteriaWeb setProjectStatus(String projectStatus) {
        this.projectStatus = projectStatus;
        return this;
    }

    public String getPublicationStatus() {
        return publicationStatus;
    }

    public SearchCriteriaWeb setPublicationStatus(String publicationStatus) {
        this.publicationStatus = publicationStatus;
        return this;
    }

    public Long getStart() {
        return start;
    }

    public SearchCriteriaWeb setStart(Long start) {
        this.start = start;
        return this;
    }

    public Boolean getScopeMyProjects() {
        Boolean scopeMyProjects = Boolean.FALSE;
        if (strScopeMyProjects != null && authenticatedUser != null) {

            // Use utility to convert checkbox to boolean         
            scopeMyProjects = new Boolean(strScopeMyProjects);
        }
        return scopeMyProjects;
    }

    public Boolean getScopePublicProjects() {
        Boolean scopePublicProjects = Boolean.FALSE;
        if (strScopePublicProjects != null) {
            scopePublicProjects = new Boolean(strScopePublicProjects);
        } else if (authenticatedUser == null) { // If there's no authenticated user, then we can only search on public projects
            scopePublicProjects = Boolean.TRUE;
        }
        return scopePublicProjects;
    }

    /**
      * Builds the GET method base URL
      * @param allTheseWords
      * @param anyTheseWords
      * @param phrase
      * @param exclude
      * @return
      */
    public String buildUrl(String baseUrl) {
        StringBuilder searchUrl = new StringBuilder();
        //searchUrl.append(this.getRequest().getHostRef().toString());
        //searchUrl.append(this.getRequest().getResourceRef().getPath());
        searchUrl.append(baseUrl);
        searchUrl.append("?x=a");
        try {
            if (queryAllTheseWords != null)
                searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_ALL_THESE_WORDS).append("=")
                        .append(URLEncoder.encode(queryAllTheseWords, SearchCriteriaWeb.URL_ENCODING));
            if (queryAnyTheseWords != null)
                searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_ANY_THESE_WORDS).append("=")
                        .append(URLEncoder.encode(queryAnyTheseWords, SearchCriteriaWeb.URL_ENCODING));
            if (queryPhrase != null)
                searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_PHRASE).append("=")
                        .append(URLEncoder.encode(queryPhrase, SearchCriteriaWeb.URL_ENCODING));
            if (queryExclude != null)
                searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_EXCLUDE).append("=")
                        .append(URLEncoder.encode(queryExclude, SearchCriteriaWeb.URL_ENCODING));
            if (startCreationDate != null)
                searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_START_DATE_CREATED).append("=")
                        .append(URLEncoder.encode(startCreationDate, SearchCriteriaWeb.URL_ENCODING));
            if (endCreationDate != null)
                searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_END_DATE_CREATED).append("=")
                        .append(URLEncoder.encode(endCreationDate, SearchCriteriaWeb.URL_ENCODING));
            if (objectTypes != null) {
                for (String objectType : objectTypes) {
                    if (objectType != null)
                        searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_OBJECT_TYPES).append("=")
                                .append(URLEncoder.encode(objectType, SearchCriteriaWeb.URL_ENCODING));
                }
            }

            if (strScopeMyProjects != null) {
                searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_SCOPE_MY_PROJECTS).append("=")
                        .append("on");
            }

            if (strScopePublicProjects != null) {
                searchUrl.append("&").append(SearchCriteriaWebFactory.INPUT_SCOPE_PUBLIC_PROJECTS).append("=")
                        .append("on");
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return searchUrl.toString();
    }

    /**
     * Convert the web format to the actual SearchCriteria object
     * @return null if there's nothing to search on
     */
    public SearchCriteria convertToSearchCriteria() {
        SearchCriteria sc = new SearchCriteriaImpl();

        if (!populateSearchCriteria(sc))
            return null;

        return sc;
    }

    /**
     * Helper method to populate a search criteria object
     * @param sc
     */
    private boolean populateSearchCriteria(SearchCriteria sc) {

        // Get the creation date range
        Date startDateCreated = null, endDateCreated = null;
        try {
            SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
            if (StringUtils.hasLength(startCreationDate))
                startDateCreated = dateFormatter.parse(startCreationDate);
            if (StringUtils.hasLength(endCreationDate))
                endDateCreated = dateFormatter.parse(endCreationDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // Get the objectTypes              
        Set<String> objectTypeCol = new HashSet<String>();
        if (objectTypes != null) {
            for (String type : objectTypes) {
                objectTypeCol.add(type);
            }
        }

        // Retrieve the list of projects for which access is allowed depending the selected scope
        // TODO: It is known that there could be some performance issues, if the number of public projects becomes too many.
        // A possible solution would be to create a new boolean field in the index called 'public', such that everytime a Project object is
        // saved, this field is updated to reflect its publication status for all objects associated with that project.
        // One of the problems of doing it the suggested way is that a project status that has changed will not immediately take affect, because
        // the index is cached. Perhaps we should flush everytime a PODD project is saved.
        Set<String> inclusiveProjectIds = new HashSet<String>();

        boolean doSearch = false;
        // If the user is administrator, and no scope has been specified, then search all projects by default
        if (authenticatedUser != null && authenticatedUser.getIsAdministrator() && !this.getScopeMyProjects()
                && !this.getScopePublicProjects()) {
            doSearch = true;
        } else {

            if (this.getScopeMyProjects()) {
                inclusiveProjectIds
                        .addAll(projectService.getAuthenticatedUserProjects(authenticatedUser.getUserName()));
            }
            // If the user is anonymous, then search on public projects
            if (authenticatedUser == null || this.getScopePublicProjects()) {
                inclusiveProjectIds.addAll(projectService.getPublicProjects());
            }

            // Only perform search if there is at least one project Id that can be searched
            doSearch = (inclusiveProjectIds.size() > 0) ? true : false;
        }
        LOGGER.info("doSearch=" + doSearch);

        sc.setQueryAllTheseWords(queryAllTheseWords);
        sc.setQueryAnyTheseWords(queryAnyTheseWords);
        sc.setQueryPhrase(queryPhrase);
        sc.setQueryExclude(queryExclude);
        sc.setStart(start);
        sc.setStartCreationDate(startDateCreated);
        sc.setEndCreationDate(endDateCreated);
        sc.setObjectTypes(objectTypeCol);
        sc.setProjectStatus(ProjectStatus.getPoddEntityState(this.getProjectStatus()));
        sc.setPublicationStatus(ProjectPublicationStatus.getStatus(this.getPublicationStatus()));
        sc.setProjectIdsInclusive(inclusiveProjectIds);

        return doSearch;
    }

    /**
     * Convert the web format to the actual UserSearchCriteria object
     * @return null if there's nothing to search on
     */
    public UserSearchCriteria convertToUserSearchCriteria() {
        UserSearchCriteria usc = new UserSearchCriteriaImpl();
        /*       
        if (! populateSearchCriteria(usc)) {
           return null;
        }*/
        populateSearchCriteria(usc);

        usc.setMyProjects(this.getScopeMyProjects());
        usc.setPublicProjects(this.getScopePublicProjects());
        usc.setUser(authenticatedUser);

        if (StringUtils.hasText(this.getProjectStatus())) {
            ProjectStatus projectStatus = ProjectStatus.getPoddEntityState(this.getProjectStatus());
            usc.setProjectStatus(projectStatus);
        }

        if (StringUtils.hasText(this.getPublicationStatus())) {
            ProjectPublicationStatus publicationStatus = ProjectPublicationStatus
                    .getStatus(this.getPublicationStatus());
            usc.setPublicationStatus(publicationStatus);
        }

        return usc;
    }

    /**
     * Convert the list of projects to their PIDs
     * @param projects
     * @return
     */
    private Collection<String> getProjectIds(Collection<Project> projects) {
        Set<String> projectIds = new HashSet<String>();

        if (projects != null) {
            for (Project project : projects) {
                if (project != null) {
                    projectIds.add(project.getPid());
                }
            }
        }

        return projectIds;
    }

}