Search in sources :

Example 6 with SearchQuery

use of org.opencastproject.search.api.SearchQuery in project opencast by opencast.

the class SeriesFeedService method loadFeedData.

/**
 * {@inheritDoc}
 *
 * @see org.opencastproject.feed.impl.AbstractFeedGenerator#loadFeedData(org.opencastproject.feed.api.Feed.Type,
 *      java.lang.String[], int, int)
 */
@Override
protected SearchResult loadFeedData(Type type, String[] query, int limit, int offset) {
    SearchQuery q = createBaseQuery(type, limit, offset);
    q.includeEpisodes(true);
    q.includeSeries(false);
    q.withSeriesId(series.get());
    return searchService.getByQuery(q);
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery)

Example 7 with SearchQuery

use of org.opencastproject.search.api.SearchQuery in project opencast by opencast.

the class SearchRestService method getEpisode.

// CHECKSTYLE:OFF
@GET
@Path("episode.{format:xml|json}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@RestQuery(name = "episodes", description = "Search for episodes matching the query parameters.", pathParameters = { @RestParameter(description = "The output format (json or xml) of the response body.", isRequired = true, name = "format", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The ID of the single episode to be returned, if it exists.", isRequired = false, name = "id", type = RestParameter.Type.STRING), @RestParameter(description = "Any episode that matches this free-text query.", isRequired = false, name = "q", type = RestParameter.Type.STRING), @RestParameter(description = "Any episode that belongs to specified series id.", isRequired = false, name = "sid", type = RestParameter.Type.STRING), // isRequired = false, name = "episodes", type = RestParameter.Type.STRING),
@RestParameter(name = "sort", isRequired = false, description = "The sort order.  May include any " + "of the following: DATE_CREATED, DATE_PUBLISHED, TITLE, SERIES_ID, MEDIA_PACKAGE_ID, CREATOR, " + "CONTRIBUTOR, LANGUAGE, LICENSE, SUBJECT, DESCRIPTION, PUBLISHER.  Add '_DESC' to reverse the sort order (e.g. TITLE_DESC).", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "20", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "false", description = "Whether this is an administrative query", isRequired = false, name = "admin", type = RestParameter.Type.BOOLEAN) }, reponses = { @RestResponse(description = "The request was processed succesfully.", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The search results, expressed as xml or json.")
public Response getEpisode(@QueryParam("id") String id, @QueryParam("q") String text, @QueryParam("sid") String seriesId, @QueryParam("sort") String sort, @QueryParam("tag") String[] tags, @QueryParam("flavor") String[] flavors, @QueryParam("limit") int limit, @QueryParam("offset") int offset, @QueryParam("admin") boolean admin, @PathParam("format") String format) throws SearchException, UnauthorizedException {
    // CHECKSTYLE:ON
    // Prepare the flavors
    List<MediaPackageElementFlavor> flavorSet = new ArrayList<MediaPackageElementFlavor>();
    if (flavors != null) {
        for (String f : flavors) {
            try {
                flavorSet.add(MediaPackageElementFlavor.parseFlavor(f));
            } catch (IllegalArgumentException e) {
                logger.debug("invalid flavor '{}' specified in query", f);
            }
        }
    }
    SearchQuery search = new SearchQuery();
    search.withId(id).withSeriesId(seriesId).withElementFlavors(flavorSet.toArray(new MediaPackageElementFlavor[flavorSet.size()])).withElementTags(tags).withLimit(limit).withOffset(offset);
    if (StringUtils.isNotBlank(text)) {
        search.withText(text);
    }
    search.withSort(SearchQuery.Sort.DATE_CREATED, false);
    if (StringUtils.isNotBlank(sort)) {
        // Parse the sort field and direction
        SearchQuery.Sort sortField = null;
        if (sort.endsWith(DESCENDING_SUFFIX)) {
            String enumKey = sort.substring(0, sort.length() - DESCENDING_SUFFIX.length()).toUpperCase();
            try {
                sortField = SearchQuery.Sort.valueOf(enumKey);
                search.withSort(sortField, false);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", enumKey);
            }
        } else {
            try {
                sortField = SearchQuery.Sort.valueOf(sort);
                search.withSort(sortField);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", sort);
            }
        }
    }
    // Build the response
    ResponseBuilder rb = Response.ok();
    if (admin) {
        rb.entity(searchService.getForAdministrativeRead(search));
    } else {
        rb.entity(searchService.getByQuery(search));
    }
    if ("json".equals(format)) {
        rb.type(MediaType.APPLICATION_JSON);
    } else {
        rb.type(MediaType.TEXT_XML);
    }
    return rb.build();
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery) ArrayList(java.util.ArrayList) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) MediaPackageElementFlavor(org.opencastproject.mediapackage.MediaPackageElementFlavor) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 8 with SearchQuery

use of org.opencastproject.search.api.SearchQuery in project opencast by opencast.

the class SearchRestService method getByLuceneQuery.

@GET
@Path("lucene.{format:xml|json}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@RestQuery(name = "lucene", description = "Search a lucene query.", pathParameters = { @RestParameter(description = "The output format (json or xml) of the response body.", isRequired = true, name = "format", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(defaultValue = "", description = "The lucene query.", isRequired = false, name = "q", type = RestParameter.Type.STRING), @RestParameter(name = "sort", isRequired = false, description = "The sort order.  May include any " + "of the following: DATE_CREATED, DATE_PUBLISHED, TITLE, SERIES_ID, MEDIA_PACKAGE_ID, CREATOR, " + "CONTRIBUTOR, LANGUAGE, LICENSE, SUBJECT, DESCRIPTION, PUBLISHER.  Add '_DESC' to reverse the sort order (e.g. TITLE_DESC).", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "20", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING), @RestParameter(defaultValue = "false", description = "Whether this is an administrative query", isRequired = false, name = "admin", type = RestParameter.Type.BOOLEAN) }, reponses = { @RestResponse(description = "The request was processed succesfully.", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "The search results, expressed as xml or json")
public Response getByLuceneQuery(@QueryParam("q") String q, @QueryParam("sort") String sort, @QueryParam("limit") int limit, @QueryParam("offset") int offset, @QueryParam("admin") boolean admin, @PathParam("format") String format) throws SearchException, UnauthorizedException {
    SearchQuery query = new SearchQuery();
    if (!StringUtils.isBlank(q))
        query.withQuery(q);
    query.withSort(SearchQuery.Sort.DATE_CREATED, false);
    if (StringUtils.isNotBlank(sort)) {
        // Parse the sort field and direction
        SearchQuery.Sort sortField = null;
        if (sort.endsWith(DESCENDING_SUFFIX)) {
            String enumKey = sort.substring(0, sort.length() - DESCENDING_SUFFIX.length()).toUpperCase();
            try {
                sortField = SearchQuery.Sort.valueOf(enumKey);
                query.withSort(sortField, false);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", enumKey);
            }
        } else {
            try {
                sortField = SearchQuery.Sort.valueOf(sort);
                query.withSort(sortField);
            } catch (IllegalArgumentException e) {
                logger.warn("No sort enum matches '{}'", sort);
            }
        }
    }
    query.withLimit(limit);
    query.withOffset(offset);
    // Build the response
    ResponseBuilder rb = Response.ok();
    if (admin) {
        rb.entity(searchService.getForAdministrativeRead(query));
    } else {
        rb.entity(searchService.getByQuery(query));
    }
    if ("json".equals(format)) {
        rb.type(MediaType.APPLICATION_JSON);
    } else {
        rb.type(MediaType.TEXT_XML);
    }
    return rb.build();
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 9 with SearchQuery

use of org.opencastproject.search.api.SearchQuery in project opencast by opencast.

the class SeriesUpdatedEventHandler method handleEvent.

public void handleEvent(final SeriesItem seriesItem) {
    // A series or its ACL has been updated. Find any mediapackages with that series, and update them.
    logger.debug("Handling {}", seriesItem);
    String seriesId = seriesItem.getSeriesId();
    // We must be an administrative user to make this query
    final User prevUser = securityService.getUser();
    final Organization prevOrg = securityService.getOrganization();
    try {
        securityService.setUser(SecurityUtil.createSystemUser(systemAccount, prevOrg));
        SearchQuery q = new SearchQuery().withSeriesId(seriesId);
        SearchResult result = searchService.getForAdministrativeRead(q);
        for (SearchResultItem item : result.getItems()) {
            MediaPackage mp = item.getMediaPackage();
            Organization org = organizationDirectoryService.getOrganization(item.getOrganization());
            securityService.setOrganization(org);
            // to the distribution channels as well
            if (SeriesItem.Type.UpdateAcl.equals(seriesItem.getType())) {
                // Build a new XACML file for this mediapackage
                Attachment fileRepoCopy = authorizationService.setAcl(mp, AclScope.Series, seriesItem.getAcl()).getB();
                // Distribute the updated XACML file
                Job distributionJob = distributionService.distribute(CHANNEL_ID, mp, fileRepoCopy.getIdentifier());
                JobBarrier barrier = new JobBarrier(null, serviceRegistry, distributionJob);
                Result jobResult = barrier.waitForJobs();
                if (jobResult.getStatus().get(distributionJob).equals(FINISHED)) {
                    mp.remove(fileRepoCopy);
                    mp.add(getFromXml(serviceRegistry.getJob(distributionJob.getId()).getPayload()));
                } else {
                    logger.error("Unable to distribute XACML {}", fileRepoCopy.getIdentifier());
                    continue;
                }
            }
            // Update the series dublin core
            if (SeriesItem.Type.UpdateCatalog.equals(seriesItem.getType())) {
                DublinCoreCatalog seriesDublinCore = seriesItem.getMetadata();
                mp.setSeriesTitle(seriesDublinCore.getFirst(DublinCore.PROPERTY_TITLE));
                // Update the series dublin core
                Catalog[] seriesCatalogs = mp.getCatalogs(MediaPackageElements.SERIES);
                if (seriesCatalogs.length == 1) {
                    Catalog c = seriesCatalogs[0];
                    String filename = FilenameUtils.getName(c.getURI().toString());
                    URI uri = workspace.put(mp.getIdentifier().toString(), c.getIdentifier(), filename, dublinCoreService.serialize(seriesDublinCore));
                    c.setURI(uri);
                    // setting the URI to a new source so the checksum will most like be invalid
                    c.setChecksum(null);
                    // Distribute the updated series dc
                    Job distributionJob = distributionService.distribute(CHANNEL_ID, mp, c.getIdentifier());
                    JobBarrier barrier = new JobBarrier(null, serviceRegistry, distributionJob);
                    Result jobResult = barrier.waitForJobs();
                    if (jobResult.getStatus().get(distributionJob).equals(FINISHED)) {
                        mp.remove(c);
                        mp.add(getFromXml(serviceRegistry.getJob(distributionJob.getId()).getPayload()));
                    } else {
                        logger.error("Unable to distribute series catalog {}", c.getIdentifier());
                        continue;
                    }
                }
            }
            // Remove the series catalog and isPartOf from episode catalog
            if (SeriesItem.Type.Delete.equals(seriesItem.getType())) {
                mp.setSeries(null);
                mp.setSeriesTitle(null);
                boolean retractSeriesCatalog = retractSeriesCatalog(mp);
                boolean updateEpisodeCatalog = updateEpisodeCatalog(mp);
                if (!retractSeriesCatalog || !updateEpisodeCatalog)
                    continue;
            }
            // Update the search index with the modified mediapackage
            Job searchJob = searchService.add(mp);
            JobBarrier barrier = new JobBarrier(null, serviceRegistry, searchJob);
            barrier.waitForJobs();
        }
    } catch (SearchException e) {
        logger.warn("Unable to find mediapackages in search: ", e.getMessage());
    } catch (UnauthorizedException e) {
        logger.warn(e.getMessage());
    } catch (MediaPackageException e) {
        logger.warn(e.getMessage());
    } catch (ServiceRegistryException e) {
        logger.warn(e.getMessage());
    } catch (NotFoundException e) {
        logger.warn(e.getMessage());
    } catch (IOException e) {
        logger.warn(e.getMessage());
    } catch (DistributionException e) {
        logger.warn(e.getMessage());
    } finally {
        securityService.setOrganization(prevOrg);
        securityService.setUser(prevUser);
    }
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery) MediaPackageException(org.opencastproject.mediapackage.MediaPackageException) User(org.opencastproject.security.api.User) Organization(org.opencastproject.security.api.Organization) SearchResultItem(org.opencastproject.search.api.SearchResultItem) SearchException(org.opencastproject.search.api.SearchException) NotFoundException(org.opencastproject.util.NotFoundException) SearchResult(org.opencastproject.search.api.SearchResult) Attachment(org.opencastproject.mediapackage.Attachment) IOException(java.io.IOException) JobBarrier(org.opencastproject.job.api.JobBarrier) URI(java.net.URI) Catalog(org.opencastproject.mediapackage.Catalog) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) Result(org.opencastproject.job.api.JobBarrier.Result) SearchResult(org.opencastproject.search.api.SearchResult) MediaPackage(org.opencastproject.mediapackage.MediaPackage) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) DistributionException(org.opencastproject.distribution.api.DistributionException) Job(org.opencastproject.job.api.Job) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog)

Example 10 with SearchQuery

use of org.opencastproject.search.api.SearchQuery in project opencast by opencast.

the class AbstractFeedGenerator method createBaseQuery.

/**
 * Creates a search query that is taking into account the flavors and tags as configured in the feed definition as
 * well as limit and offset passed into this method.
 *
 * @param type
 *          the requested feed type
 * @param limit
 *          the number of entries
 * @param offset
 *          the starting entry
 * @return the base query
 */
protected SearchQuery createBaseQuery(Feed.Type type, int limit, int offset) {
    SearchQuery searchQuery = new SearchQuery();
    searchQuery.withLimit(limit);
    searchQuery.withOffset(offset);
    searchQuery.withSort(SearchQuery.Sort.DATE_CREATED);
    switch(type) {
        case Atom:
            if (atomTags != null && atomTags.size() > 0)
                searchQuery.withElementTags(atomTags.toArray(new String[atomTags.size()]));
            break;
        case RSS:
            if (rssTags != null && rssTags.size() > 0)
                searchQuery.withElementTags(rssTags.toArray(new String[rssTags.size()]));
            break;
        default:
            throw new IllegalStateException("Unknown feed type '" + type + "' is not supported");
    }
    return searchQuery;
}
Also used : SearchQuery(org.opencastproject.search.api.SearchQuery)

Aggregations

SearchQuery (org.opencastproject.search.api.SearchQuery)25 MediaPackage (org.opencastproject.mediapackage.MediaPackage)14 Job (org.opencastproject.job.api.Job)12 Test (org.junit.Test)11 JobBarrier (org.opencastproject.job.api.JobBarrier)10 SearchResult (org.opencastproject.search.api.SearchResult)10 AccessControlEntry (org.opencastproject.security.api.AccessControlEntry)5 ArrayList (java.util.ArrayList)4 Date (java.util.Date)4 GET (javax.ws.rs.GET)3 Path (javax.ws.rs.Path)3 Produces (javax.ws.rs.Produces)3 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)3 User (org.opencastproject.security.api.User)3 RestQuery (org.opencastproject.util.doc.rest.RestQuery)3 WorkflowOperationException (org.opencastproject.workflow.api.WorkflowOperationException)3 SearchException (org.opencastproject.search.api.SearchException)2 SearchResultItem (org.opencastproject.search.api.SearchResultItem)2 JaxbRole (org.opencastproject.security.api.JaxbRole)2 JaxbUser (org.opencastproject.security.api.JaxbUser)2