Search in sources :

Example 31 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project SearchServices by Alfresco.

the class AbstractQParser method getSearchParameters.

protected Pair<SearchParameters, Boolean> getSearchParameters() {
    SearchParameters searchParameters = new SearchParameters();
    Boolean isFilter = Boolean.FALSE;
    Iterable<ContentStream> streams = req.getContentStreams();
    JSONObject json = (JSONObject) req.getContext().get(ALFRESCO_JSON);
    if (json == null) {
        if (streams != null) {
            try {
                Reader reader = null;
                for (ContentStream stream : streams) {
                    reader = new BufferedReader(new InputStreamReader(stream.getStream(), "UTF-8"));
                }
                // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
                if (reader != null) {
                    json = new JSONObject(new JSONTokener(reader));
                    req.getContext().put(ALFRESCO_JSON, json);
                }
            } catch (JSONException e) {
            // This is expected when there is no json element to the request
            } catch (IOException e) {
                throw new AlfrescoRuntimeException("IO Error parsing query parameters", e);
            }
        }
    }
    if (json != null) {
        try {
            if (getString() != null) {
                if (getString().equals(AUTHORITY_FILTER_FROM_JSON)) {
                    isFilter = Boolean.TRUE;
                    ArrayList<String> tenantList = new ArrayList<String>(1);
                    JSONArray tenants = json.getJSONArray("tenants");
                    for (int i = 0; i < tenants.length(); i++) {
                        String tenantString = tenants.getString(i);
                        tenantList.add(tenantString);
                    }
                    ArrayList<String> authorityList = new ArrayList<String>(1);
                    JSONArray authorities = json.getJSONArray("authorities");
                    for (int i = 0; i < authorities.length(); i++) {
                        String authorityString = authorities.getString(i);
                        authorityList.add(authorityString);
                    }
                    char separator = getSeparator(authorityList);
                    StringBuilder authQuery = new StringBuilder();
                    StringBuilder denyQuery = new StringBuilder();
                    for (String tenant : tenantList) {
                        for (String authority : authorityList) {
                            if (separator == 0) {
                                if (authQuery.length() > 0) {
                                    authQuery.append(" ");
                                    denyQuery.append(" ");
                                }
                                switch(AuthorityType.getAuthorityType(authority)) {
                                    case USER:
                                        authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
                                        denyQuery.append("|DENIED:\"").append(authority).append("\"");
                                        break;
                                    case GROUP:
                                    case EVERYONE:
                                    case GUEST:
                                        if (tenant.length() == 0) {
                                            // Default tenant matches 4.0
                                            authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
                                            denyQuery.append("|DENIED:\"").append(authority).append("\"");
                                        } else {
                                            authQuery.append("|AUTHORITY:\"").append(authority).append("@").append(tenant).append("\"");
                                            denyQuery.append("|DENIED:\"").append(authority).append("@").append(tenant).append("\"");
                                        }
                                        break;
                                    default:
                                        authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
                                        denyQuery.append("|DENIED:\"").append(authority).append("\"");
                                        break;
                                }
                            } else {
                                if (authQuery.length() == 0) {
                                    authset = true;
                                    authQuery.append("|AUTHSET:\"");
                                    denyQuery.append("|DENYSET:\"");
                                }
                                switch(AuthorityType.getAuthorityType(authority)) {
                                    case USER:
                                        authQuery.append(separator).append(authority);
                                        denyQuery.append(separator).append(authority);
                                        break;
                                    case GROUP:
                                    case EVERYONE:
                                    case GUEST:
                                        if (tenant.length() == 0) {
                                            // Default tenant matches 4.0
                                            authQuery.append(separator).append(authority);
                                            denyQuery.append(separator).append(authority);
                                        } else {
                                            authQuery.append(separator).append(authority).append("@").append(tenant);
                                            denyQuery.append(separator).append(authority).append("@").append(tenant);
                                        }
                                        break;
                                    default:
                                        authQuery.append(separator).append(authority);
                                        denyQuery.append(separator).append(authority);
                                        break;
                                }
                            }
                        }
                    }
                    if (separator != 0) {
                        authQuery.append("\"");
                        denyQuery.append("\"");
                    }
                    if (authQuery.length() > 0) {
                        // Default to true for safety reasons.
                        final boolean anyDenyDenies = json.optBoolean("anyDenyDenies", true);
                        if (anyDenyDenies) {
                            authQuery.insert(0, "(").append(") AND NOT (").append(denyQuery).append(")");
                            // Record that the clause has been added.
                            // We only ever set this to true for solr4+
                            req.getContext().put("processedDenies", Boolean.TRUE);
                        }
                        searchParameters.setQuery(authQuery.toString());
                    }
                } else if (getString().equals(TENANT_FILTER_FROM_JSON)) {
                    isFilter = Boolean.TRUE;
                    ArrayList<String> tenantList = new ArrayList<String>(1);
                    JSONArray tenants = json.getJSONArray("tenants");
                    for (int i = 0; i < tenants.length(); i++) {
                        String tenantString = tenants.getString(i);
                        tenantList.add(tenantString);
                    }
                    StringBuilder tenantQuery = new StringBuilder();
                    for (String tenant : tenantList) {
                        if (tenantQuery.length() > 0) {
                            tenantQuery.append(" ");
                        }
                        if (tenant.length() > 0) {
                            tenantQuery.append("|TENANT:\"").append(tenant).append("\"");
                        } else {
                            // TODO: Need to check for the default tenant or no tenant (4.0) or we force a reindex
                            // requirement later ...
                            // Better to add default tenant to the 4.0 index
                            tenantQuery.append("|TENANT:\"").append("_DEFAULT_").append("\"");
                        // tenantQuery.append(" |(+ISNODE:T -TENANT:*)");
                        }
                    }
                    searchParameters.setQuery(tenantQuery.toString());
                } else if (getString().equals(RERANK_QUERY_FROM_CONTEXT)) {
                    String searchTerm = getParam("spellcheck.q");
                    searchParameters.setQuery(searchTerm);
                }
            } else {
                String query = json.getString("query");
                if (query != null) {
                    searchParameters.setQuery(query);
                }
            }
            JSONArray locales = json.getJSONArray("locales");
            for (int i = 0; i < locales.length(); i++) {
                String localeString = locales.getString(i);
                Locale locale = DefaultTypeConverter.INSTANCE.convert(Locale.class, localeString);
                searchParameters.addLocale(locale);
            }
            JSONArray templates = json.getJSONArray("templates");
            for (int i = 0; i < templates.length(); i++) {
                JSONObject template = templates.getJSONObject(i);
                String name = template.getString("name");
                String queryTemplate = template.getString("template");
                searchParameters.addQueryTemplate(name, queryTemplate);
            }
            JSONArray allAttributes = json.getJSONArray("allAttributes");
            for (int i = 0; i < allAttributes.length(); i++) {
                String allAttribute = allAttributes.getString(i);
                searchParameters.addAllAttribute(allAttribute);
            }
            searchParameters.setDefaultFTSOperator(Operator.valueOf(json.getString("defaultFTSOperator")));
            searchParameters.setDefaultFTSFieldConnective(Operator.valueOf(json.getString("defaultFTSFieldOperator")));
            if (json.has("mlAnalaysisMode")) {
                searchParameters.setMlAnalaysisMode(MLAnalysisMode.valueOf(json.getString("mlAnalaysisMode")));
            }
            searchParameters.setNamespace(json.getString("defaultNamespace"));
            JSONArray textAttributes = json.getJSONArray("textAttributes");
            for (int i = 0; i < textAttributes.length(); i++) {
                String textAttribute = textAttributes.getString(i);
                searchParameters.addTextAttribute(textAttribute);
            }
            searchParameters.setQueryConsistency(QueryConsistency.valueOf(json.getString("queryConsistency")));
        } catch (JSONException e) {
        // This is expected when there is no json element to the request
        }
    }
    if (json != null) {
        if (log.isDebugEnabled()) {
            log.debug(json.toString());
        }
    }
    if (searchParameters.getQuery() == null) {
        searchParameters.setQuery(getString());
    }
    if (searchParameters.getLocales().size() == 0) {
        searchParameters.addLocale(I18NUtil.getLocale());
    }
    String defaultField = getParam(CommonParams.DF);
    if (defaultField != null) {
        searchParameters.setDefaultFieldName(defaultField);
    }
    if (autoDetectQueryLocale) {
        String searchTerm = getParam("spellcheck.q");
        if (searchTerm != null) {
            searchParameters.setSearchTerm(searchTerm);
            List<DetectedLanguage> detetcted = detectLanguage(searchTerm);
            if ((detetcted != null) && (detetcted.size() > 0)) {
                Locale detectedLocale = Locale.forLanguageTag(detetcted.get(0).getLangCode());
                if (localeIsNotIncluded(searchParameters, detectedLocale)) {
                    searchParameters.addLocale(Locale.forLanguageTag(detectedLocale.getLanguage()));
                }
            }
        }
    }
    if (fixedQueryLocales.size() > 0) {
        for (String locale : fixedQueryLocales) {
            searchParameters.addLocale(Locale.forLanguageTag(locale));
        }
    }
    // searchParameters.setMlAnalaysisMode(getMLAnalysisMode());
    searchParameters.setNamespace(NamespaceService.CONTENT_MODEL_1_0_URI);
    return new Pair<SearchParameters, Boolean>(searchParameters, isFilter);
}
Also used : Locale(java.util.Locale) InputStreamReader(java.io.InputStreamReader) ArrayList(java.util.ArrayList) JSONArray(org.json.JSONArray) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JSONException(org.json.JSONException) IOException(java.io.IOException) JSONTokener(org.json.JSONTokener) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) ContentStream(org.apache.solr.common.util.ContentStream) JSONObject(org.json.JSONObject) BufferedReader(java.io.BufferedReader) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) Pair(org.alfresco.util.Pair)

Example 32 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class QuickShareLinksImpl method findLinks.

public CollectionWithPagingInfo<QuickShareLink> findLinks(Parameters parameters) {
    checkEnabled();
    String queryString = "ASPECT:\"" + QuickShareModel.ASPECT_QSHARE.toString() + "\"";
    SearchParameters sp = new SearchParameters();
    // note: REST API query parameter (ie. where clause filter) - not to be confused with search query ;-)
    Query q = parameters.getQuery();
    if (q != null) {
        // filtering via "where" clause
        MapBasedQueryWalker propertyWalker = new MapBasedQueryWalker(FIND_SHARED_LINKS_QUERY_PROPERTIES, null);
        QueryHelper.walk(q, propertyWalker);
        String sharedByUserId = propertyWalker.getProperty(PARAM_SHAREDBY, WhereClauseParser.EQUALS, String.class);
        if (sharedByUserId != null) {
            if (People.DEFAULT_USER.equalsIgnoreCase(sharedByUserId)) {
                sharedByUserId = AuthenticationUtil.getFullyAuthenticatedUser();
            }
            QueryParameterDefinition qpd = new QueryParameterDefImpl(QuickShareModel.PROP_QSHARE_SHAREDBY, dictionaryService.getDataType(DataTypeDefinition.TEXT), true, sharedByUserId);
            sp.addQueryParameterDefinition(qpd);
            String qsharedBy = QuickShareModel.PROP_QSHARE_SHAREDBY.toPrefixString(namespaceService);
            queryString += " +@" + SearchLanguageConversion.escapeLuceneQuery(qsharedBy) + ":\"${" + qsharedBy + "}\"";
        }
    }
    sp.setLanguage(SearchService.LANGUAGE_LUCENE);
    sp.setQuery(queryString);
    sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    Paging paging = parameters.getPaging();
    PagingRequest pagingRequest = Util.getPagingRequest(paging);
    sp.setSkipCount(pagingRequest.getSkipCount());
    sp.setMaxItems(pagingRequest.getMaxItems());
    sp.addSort("@" + ContentModel.PROP_MODIFIED, false);
    ResultSet results = searchService.query(sp);
    List<QuickShareLink> qsLinks = new ArrayList<>(results.length());
    List<String> includeParam = parameters.getInclude();
    for (ResultSetRow row : results) {
        NodeRef nodeRef = row.getNodeRef();
        qsLinks.add(getQuickShareInfo(nodeRef, false, includeParam));
    }
    results.close();
    return CollectionWithPagingInfo.asPaged(paging, qsLinks, results.hasMore(), Long.valueOf(results.getNumberFound()).intValue());
}
Also used : QueryParameterDefImpl(org.alfresco.repo.search.QueryParameterDefImpl) Query(org.alfresco.rest.framework.resource.parameters.where.Query) Paging(org.alfresco.rest.framework.resource.parameters.Paging) ArrayList(java.util.ArrayList) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) PagingRequest(org.alfresco.query.PagingRequest) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) NodeRef(org.alfresco.service.cmr.repository.NodeRef) MapBasedQueryWalker(org.alfresco.rest.workflow.api.impl.MapBasedQueryWalker) ResultSet(org.alfresco.service.cmr.search.ResultSet) QuickShareLink(org.alfresco.rest.api.model.QuickShareLink) QueryParameterDefinition(org.alfresco.service.cmr.search.QueryParameterDefinition)

Example 33 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class SearchApiWebscript method execute.

@Override
public void execute(WebScriptRequest webScriptRequest, WebScriptResponse webScriptResponse) throws IOException {
    try {
        // Turn JSON into a Java object respresentation
        SearchQuery searchQuery = extractJsonContent(webScriptRequest, assistant.getJsonHelper(), SearchQuery.class);
        // Parse the parameters
        Params params = getParams(webScriptRequest, searchQuery.getFields(), searchQuery.getInclude(), searchQuery.getPaging());
        // Make a copy of the request
        SearchRequestContext searchRequestContext = SearchRequestContext.from(searchQuery);
        // Turn the SearchQuery json into the Java SearchParameters object
        SearchParameters searchParams = searchMapper.toSearchParameters(params, searchQuery, searchRequestContext);
        // Call searchService
        ResultSet results = searchService.query(searchParams);
        // Turn solr results into JSON
        CollectionWithPagingInfo<Node> resultJson = resultMapper.toCollectionWithPagingInfo(params, searchRequestContext, searchQuery, results);
        // Post-process the request and pass in params, eg. params.getFilter()
        Object toRender = helper.processAdditionsToTheResponse(null, null, null, params, resultJson);
        // Write response
        setResponse(webScriptResponse, DEFAULT_SUCCESS);
        renderJsonResponse(webScriptResponse, toRender, assistant.getJsonHelper());
    } catch (Exception exception) {
        renderException(exception, webScriptResponse, assistant);
    }
}
Also used : SearchQuery(org.alfresco.rest.api.search.model.SearchQuery) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) Node(org.alfresco.rest.api.model.Node) ResultSet(org.alfresco.service.cmr.search.ResultSet) Params(org.alfresco.rest.framework.resource.parameters.Params) SearchRequestContext(org.alfresco.rest.api.search.context.SearchRequestContext) IOException(java.io.IOException)

Example 34 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class SearchSQLApiWebscript method buildSearchParameters.

public SearchParameters buildSearchParameters(SearchSQLQuery searchQuery) {
    SearchParameters sparams = new SearchParameters();
    sparams.setLanguage(SearchService.LANGUAGE_SOLR_SQL);
    sparams.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
    if (StringUtils.isEmpty(searchQuery.getStmt())) {
        throw new AlfrescoRuntimeException("Required stmt parameter is missing.");
    }
    sparams.setQuery(searchQuery.getStmt());
    searchQuery.getLocales().forEach(action -> {
        Locale locale = new Locale(action);
        sparams.addLocale(locale);
    });
    return sparams;
}
Also used : Locale(java.util.Locale) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 35 with SearchParameters

use of org.alfresco.service.cmr.search.SearchParameters in project alfresco-remote-api by Alfresco.

the class SearchSQLApiWebscript method execute.

@Override
public void execute(WebScriptRequest webScriptRequest, WebScriptResponse res) throws IOException {
    try {
        // Turn JSON into a Java object representation
        SearchSQLQuery searchQuery = extractJsonContent(webScriptRequest, assistant.getJsonHelper(), SearchSQLQuery.class);
        SearchParameters sparams = buildSearchParameters(searchQuery);
        ResultSet results = searchService.query(sparams);
        FilteringResultSet frs = (FilteringResultSet) results;
        SolrSQLJSONResultSet ssjr = (SolrSQLJSONResultSet) frs.getUnFilteredResultSet();
        // When solr format is requested pass the solr output directly.
        if (searchQuery.getFormat().equalsIgnoreCase("solr")) {
            res.getWriter().write(ssjr.getSolrResponse());
        } else {
            CollectionWithPagingInfo<TupleList> nodes = resultMapper.toCollectionWithPagingInfo(ssjr.getDocs(), searchQuery);
            renderJsonResponse(res, nodes, assistant.getJsonHelper());
        }
        setResponse(res, DEFAULT_SUCCESS);
    } catch (Exception exception) {
        renderException(exception, res, assistant);
    }
}
Also used : FilteringResultSet(org.alfresco.repo.security.permissions.impl.acegi.FilteringResultSet) TupleList(org.alfresco.rest.api.search.model.TupleList) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) SolrSQLJSONResultSet(org.alfresco.repo.search.impl.solr.SolrSQLJSONResultSet) ResultSet(org.alfresco.service.cmr.search.ResultSet) FilteringResultSet(org.alfresco.repo.security.permissions.impl.acegi.FilteringResultSet) SolrSQLJSONResultSet(org.alfresco.repo.search.impl.solr.SolrSQLJSONResultSet) SearchSQLQuery(org.alfresco.rest.api.search.model.SearchSQLQuery) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Aggregations

SearchParameters (org.alfresco.service.cmr.search.SearchParameters)56 Test (org.junit.Test)28 ResultSet (org.alfresco.service.cmr.search.ResultSet)20 NodeRef (org.alfresco.service.cmr.repository.NodeRef)19 ArrayList (java.util.ArrayList)15 SearchRequestContext (org.alfresco.rest.api.search.context.SearchRequestContext)11 IOException (java.io.IOException)10 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)10 HashMap (java.util.HashMap)8 SearchQuery (org.alfresco.rest.api.search.model.SearchQuery)8 JSONObject (org.json.JSONObject)8 List (java.util.List)7 QName (org.alfresco.service.namespace.QName)7 JSONTokener (org.json.JSONTokener)7 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)6 SearchSQLQuery (org.alfresco.rest.api.search.model.SearchSQLQuery)6 Params (org.alfresco.rest.framework.resource.parameters.Params)6 StoreRef (org.alfresco.service.cmr.repository.StoreRef)6 GeneralHighlightParameters (org.alfresco.service.cmr.search.GeneralHighlightParameters)6 JSONArray (org.json.JSONArray)6