Search in sources :

Example 21 with Pair

use of org.alfresco.util.Pair in project SearchServices by Alfresco.

the class Solr4QueryParser method parseDateString.

private Pair<Date, Integer> parseDateString(String dateString) {
    try {
        Pair<Date, Integer> result = CachingDateFormat.lenientParse(dateString, Calendar.YEAR);
        return result;
    } catch (java.text.ParseException e) {
        SimpleDateFormat oldDf = CachingDateFormat.getDateFormat();
        try {
            Date date = oldDf.parse(dateString);
            return new Pair<Date, Integer>(date, Calendar.SECOND);
        } catch (java.text.ParseException ee) {
            if (dateString.equalsIgnoreCase("min")) {
                Calendar cal = Calendar.getInstance(I18NUtil.getLocale());
                cal.set(Calendar.YEAR, cal.getMinimum(Calendar.YEAR));
                cal.set(Calendar.DAY_OF_YEAR, cal.getMinimum(Calendar.DAY_OF_YEAR));
                cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
                cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
                cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
                cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
                return new Pair<Date, Integer>(cal.getTime(), Calendar.MILLISECOND);
            } else if (dateString.equalsIgnoreCase("now")) {
                return new Pair<Date, Integer>(new Date(), Calendar.MILLISECOND);
            } else if (dateString.equalsIgnoreCase("today")) {
                Calendar cal = Calendar.getInstance(I18NUtil.getLocale());
                cal.setTime(new Date());
                cal.set(Calendar.HOUR_OF_DAY, cal.getMinimum(Calendar.HOUR_OF_DAY));
                cal.set(Calendar.MINUTE, cal.getMinimum(Calendar.MINUTE));
                cal.set(Calendar.SECOND, cal.getMinimum(Calendar.SECOND));
                cal.set(Calendar.MILLISECOND, cal.getMinimum(Calendar.MILLISECOND));
                return new Pair<Date, Integer>(cal.getTime(), Calendar.DAY_OF_MONTH);
            } else if (dateString.equalsIgnoreCase("max")) {
                Calendar cal = Calendar.getInstance(I18NUtil.getLocale());
                cal.set(Calendar.YEAR, cal.getMaximum(Calendar.YEAR));
                cal.set(Calendar.DAY_OF_YEAR, cal.getMaximum(Calendar.DAY_OF_YEAR));
                cal.set(Calendar.HOUR_OF_DAY, cal.getMaximum(Calendar.HOUR_OF_DAY));
                cal.set(Calendar.MINUTE, cal.getMaximum(Calendar.MINUTE));
                cal.set(Calendar.SECOND, cal.getMaximum(Calendar.SECOND));
                cal.set(Calendar.MILLISECOND, cal.getMaximum(Calendar.MILLISECOND));
                return new Pair<Date, Integer>(cal.getTime(), Calendar.MILLISECOND);
            } else {
                // delegate to SOLR date parsing
                return null;
            }
        }
    }
}
Also used : Calendar(java.util.Calendar) ParseException(org.apache.lucene.queryparser.classic.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) Pair(org.alfresco.util.Pair)

Example 22 with Pair

use of org.alfresco.util.Pair in project acs-community-packaging by Alfresco.

the class BaseInviteUsersWizard method pickerCallback.

/**
 * Query callback method executed by the Generic Picker component.
 * This method is part of the contract to the Generic Picker, it is up to the backing bean
 * to execute whatever query is appropriate and return the results.
 *
 * @param filterIndex        Index of the filter drop-down selection
 * @param contains           Text from the contains textbox
 *
 * @return An array of SelectItem objects containing the results to display in the picker.
 */
public SelectItem[] pickerCallback(int filterIndex, String contains) {
    FacesContext context = FacesContext.getCurrentInstance();
    // quick exit if not enough characters entered for a search
    String search = contains.trim();
    int searchMin = Application.getClientConfig(context).getPickerSearchMinimum();
    if (search.length() < searchMin) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, MSG_SEARCH_MINIMUM), searchMin));
        return new SelectItem[0];
    }
    SelectItem[] items;
    this.maxUsersReturned = false;
    UserTransaction tx = null;
    try {
        tx = Repository.getUserTransaction(context, true);
        tx.begin();
        int maxResults = Application.getClientConfig(context).getInviteUsersMaxResults();
        if (maxResults <= 0) {
            maxResults = Utils.getPersonMaxResults();
        }
        List<SelectItem> results;
        if (filterIndex == 0) {
            // Use lucene search to retrieve user details
            List<Pair<QName, String>> filter = null;
            if (search == null || search.length() == 0) {
            // if there is no search term, search for all people
            } else {
                filter = Utils.generatePersonFilter(search);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Maximum invite users results size: " + maxResults);
                logger.debug("Using query filter to find users: " + filter);
            }
            List<PersonInfo> persons = getPersonService().getPeople(filter, true, Utils.generatePersonSort(), new PagingRequest(maxResults, null)).getPage();
            results = new ArrayList<SelectItem>(persons.size());
            for (int index = 0; index < persons.size(); index++) {
                PersonInfo person = persons.get(index);
                String firstName = person.getFirstName();
                String lastName = person.getLastName();
                String username = person.getUserName();
                if (username != null) {
                    String name = (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : "");
                    SelectItem item = new SortableSelectItem(username, name + " [" + username + "]", lastName != null ? lastName : username);
                    results.add(item);
                }
            }
        } else {
            results = addGroupItems(search, maxResults);
        }
        items = new SelectItem[results.size()];
        results.toArray(items);
        Arrays.sort(items);
        // set the maximum users returned flag if appropriate
        if (results.size() == maxResults) {
            this.maxUsersReturned = true;
        }
        // commit the transaction
        tx.commit();
    } catch (BooleanQuery.TooManyClauses clauses) {
        Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), "too_many_users"));
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
        items = new SelectItem[0];
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
        items = new SelectItem[0];
    }
    return items;
}
Also used : UserTransaction(javax.transaction.UserTransaction) FacesContext(javax.faces.context.FacesContext) BooleanQuery(org.apache.lucene.search.BooleanQuery) PersonInfo(org.alfresco.service.cmr.security.PersonService.PersonInfo) SortableSelectItem(org.alfresco.web.ui.common.SortableSelectItem) PagingRequest(org.alfresco.query.PagingRequest) IOException(java.io.IOException) AccessDeniedException(org.alfresco.repo.security.permissions.AccessDeniedException) SortableSelectItem(org.alfresco.web.ui.common.SortableSelectItem) SelectItem(javax.faces.model.SelectItem) Pair(org.alfresco.util.Pair)

Example 23 with Pair

use of org.alfresco.util.Pair in project acs-community-packaging by Alfresco.

the class DeleteUserDialog method search.

public String search() {
    if (this.searchCriteria == null || this.searchCriteria.length() == 0) {
        this.users = Collections.<Node>emptyList();
    } else {
        FacesContext context = FacesContext.getCurrentInstance();
        UserTransaction tx = null;
        try {
            tx = Repository.getUserTransaction(context, true);
            tx.begin();
            // define the query to find people by their first or last name
            String search = ISO9075.encode(this.searchCriteria);
            List<Pair<QName, String>> filter = Utils.generatePersonFilter(search);
            if (logger.isDebugEnabled()) {
                logger.debug("Query filter: " + filter);
            }
            List<PersonInfo> persons = getPersonService().getPeople(filter, true, Utils.generatePersonSort(), new PagingRequest(Utils.getPersonMaxResults(), null)).getPage();
            if (logger.isDebugEnabled()) {
                logger.debug("Found " + persons.size() + " users");
            }
            this.users = new ArrayList<Node>(persons.size());
            for (PersonInfo person : persons) {
                // create our Node representation
                MapNode node = new MapNode(person.getNodeRef());
                // set data binding properties
                // this will also force initialisation of the props now during the UserTransaction
                // it is much better for performance to do this now rather than during page bind
                Map<String, Object> props = node.getProperties();
                props.put("fullName", ((String) props.get("firstName")) + ' ' + ((String) props.get("lastName")));
                NodeRef homeFolderNodeRef = (NodeRef) props.get("homeFolder");
                if (homeFolderNodeRef != null) {
                    props.put("homeSpace", homeFolderNodeRef);
                }
                this.users.add(node);
            }
            // commit the transaction
            tx.commit();
        } catch (InvalidNodeRefException refErr) {
            Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_NODEREF), new Object[] { "root" }));
            this.users = Collections.<Node>emptyList();
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        } catch (Exception err) {
            Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err);
            this.users = Collections.<Node>emptyList();
            try {
                if (tx != null) {
                    tx.rollback();
                }
            } catch (Exception tex) {
            }
        }
    }
    // return null to stay on the same page
    return null;
}
Also used : UserTransaction(javax.transaction.UserTransaction) FacesContext(javax.faces.context.FacesContext) PersonInfo(org.alfresco.service.cmr.security.PersonService.PersonInfo) Node(org.alfresco.web.bean.repository.Node) MapNode(org.alfresco.web.bean.repository.MapNode) MapNode(org.alfresco.web.bean.repository.MapNode) PagingRequest(org.alfresco.query.PagingRequest) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) ReportedException(org.alfresco.web.ui.common.ReportedException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) Pair(org.alfresco.util.Pair)

Example 24 with Pair

use of org.alfresco.util.Pair in project SearchServices by Alfresco.

the class AlfrescoSolrUtils method getNodeMetaData.

/**
 * Get a nodes meta data.
 * @param node
 * @param txn
 * @param acl
 * @param owner
 * @param ancestors
 * @param createError
 * @return {@link NodeMetaData}
 */
public static NodeMetaData getNodeMetaData(Node node, Transaction txn, Acl acl, String owner, Set<NodeRef> ancestors, boolean createError) {
    NodeMetaData nodeMetaData = new NodeMetaData();
    nodeMetaData.setId(node.getId());
    nodeMetaData.setAclId(acl.getId());
    nodeMetaData.setTxnId(txn.getId());
    nodeMetaData.setOwner(owner);
    nodeMetaData.setAspects(new HashSet<QName>());
    nodeMetaData.setAncestors(ancestors);
    Map<QName, PropertyValue> props = new HashMap<QName, PropertyValue>();
    props.put(ContentModel.PROP_IS_INDEXED, new StringPropertyValue("true"));
    props.put(ContentModel.PROP_CONTENT, new ContentPropertyValue(Locale.US, 0l, "UTF-8", "text/plain", null));
    nodeMetaData.setProperties(props);
    // If create createError is true then we leave out the nodeRef which will cause an error
    if (!createError) {
        NodeRef nodeRef = new NodeRef(new StoreRef("workspace", "SpacesStore"), createGUID());
        nodeMetaData.setNodeRef(nodeRef);
    }
    nodeMetaData.setType(QName.createQName(TEST_NAMESPACE, "testSuperType"));
    nodeMetaData.setAncestors(ancestors);
    nodeMetaData.setPaths(new ArrayList<Pair<String, QName>>());
    nodeMetaData.setNamePaths(new ArrayList<List<String>>());
    return nodeMetaData;
}
Also used : StringPropertyValue(org.alfresco.solr.client.StringPropertyValue) StoreRef(org.alfresco.service.cmr.repository.StoreRef) NodeMetaData(org.alfresco.solr.client.NodeMetaData) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QName(org.alfresco.service.namespace.QName) ContentPropertyValue(org.alfresco.solr.client.ContentPropertyValue) PropertyValue(org.alfresco.solr.client.PropertyValue) StringPropertyValue(org.alfresco.solr.client.StringPropertyValue) ContentPropertyValue(org.alfresco.solr.client.ContentPropertyValue) NodeRef(org.alfresco.service.cmr.repository.NodeRef) List(java.util.List) ArrayList(java.util.ArrayList) NamedList(org.apache.solr.common.util.NamedList) Pair(org.alfresco.util.Pair)

Example 25 with Pair

use of org.alfresco.util.Pair 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)

Aggregations

Pair (org.alfresco.util.Pair)61 ArrayList (java.util.ArrayList)34 NodeRef (org.alfresco.service.cmr.repository.NodeRef)23 QName (org.alfresco.service.namespace.QName)22 HashMap (java.util.HashMap)16 PagingRequest (org.alfresco.query.PagingRequest)13 Paging (org.alfresco.rest.framework.resource.parameters.Paging)12 List (java.util.List)11 Serializable (java.io.Serializable)10 HashSet (java.util.HashSet)9 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)9 Set (java.util.Set)8 Map (java.util.Map)7 EntityNotFoundException (org.alfresco.rest.framework.core.exceptions.EntityNotFoundException)7 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)7 AbstractList (java.util.AbstractList)6 Arrays (java.util.Arrays)6 Collections (java.util.Collections)6 PagingResults (org.alfresco.query.PagingResults)6 Node (org.alfresco.rest.api.model.Node)6