Search in sources :

Example 1 with ListProviderException

use of org.opencastproject.index.service.exception.ListProviderException in project opencast by opencast.

the class JSONUtilsTest method testFiltersToJSON.

/**
 * Test method for
 * {@link JSONUtils#filtersToJSON(org.opencastproject.index.service.resources.list.api.ResourceListQuery, org.opencastproject.index.service.resources.list.api.ListProvidersService, org.opencastproject.security.api.Organization)}
 * (filters, listProviderService, query, org)}
 */
@Test
public void testFiltersToJSON() throws Exception {
    String expectedJSON = IOUtils.toString(getClass().getResource("/filters.json"));
    JaxbOrganization defaultOrganization = new DefaultOrganization();
    ListProvidersServiceImpl listProvidersService = new ListProvidersServiceImpl();
    SimpleSerializer serializer = new SimpleSerializer();
    final Map<String, String> license = new HashMap<String, String>();
    license.put("contributor1", "My first contributor");
    license.put("contributor2", "My second contributor");
    license.put("contributor3", "My third contributor");
    // Create test list provider
    listProvidersService.addProvider(new ResourceListProvider() {

        @Override
        public String[] getListNames() {
            return new String[] { ContributorsListProvider.DEFAULT };
        }

        @Override
        public Map<String, String> getList(String listName, ResourceListQuery query, Organization organization) throws ListProviderException {
            return ListProviderUtil.filterMap(license, query);
        }

        @Override
        public boolean isTranslatable(String listName) {
            return false;
        }

        @Override
        public String getDefault() {
            return null;
        }
    });
    // Prepare mock query
    List<ResourceListFilter<?>> filters = new ArrayList<ResourceListFilter<?>>();
    filters.add(SeriesListQuery.createContributorsFilter(Option.<String>none()));
    filters.add(new StringListFilter(""));
    ResourceListQueryImpl query = EasyMock.createNiceMock(ResourceListQueryImpl.class);
    EasyMock.expect(query.getAvailableFilters()).andReturn(filters).anyTimes();
    EasyMock.expect(query.getFilters()).andReturn(new ArrayList<ResourceListFilter<?>>()).anyTimes();
    EasyMock.expect(query.getLimit()).andReturn(Option.<Integer>none()).anyTimes();
    EasyMock.expect(query.getOffset()).andReturn(Option.<Integer>none()).anyTimes();
    EasyMock.replay(query);
    JValue result = JSONUtils.filtersToJSON(query, listProvidersService, defaultOrganization);
    StreamingOutput stream = RestUtils.stream(serializer.fn.toJson(result));
    ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
    try {
        stream.write(resultStream);
        assertThat(expectedJSON, SameJSONAs.sameJSONAs(resultStream.toString()));
    } finally {
        IOUtils.closeQuietly(resultStream);
    }
}
Also used : SimpleSerializer(com.entwinemedia.fn.data.json.SimpleSerializer) ResourceListProvider(org.opencastproject.index.service.resources.list.api.ResourceListProvider) Organization(org.opencastproject.security.api.Organization) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) ListProvidersServiceImpl(org.opencastproject.index.service.resources.list.impl.ListProvidersServiceImpl) HashMap(java.util.HashMap) JaxbOrganization(org.opencastproject.security.api.JaxbOrganization) ArrayList(java.util.ArrayList) ListProviderException(org.opencastproject.index.service.exception.ListProviderException) ResourceListQueryImpl(org.opencastproject.index.service.resources.list.query.ResourceListQueryImpl) StreamingOutput(javax.ws.rs.core.StreamingOutput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ResourceListQuery(org.opencastproject.index.service.resources.list.api.ResourceListQuery) ResourceListFilter(org.opencastproject.index.service.resources.list.api.ResourceListFilter) JValue(com.entwinemedia.fn.data.json.JValue) HashMap(java.util.HashMap) Map(java.util.Map) DefaultOrganization(org.opencastproject.security.api.DefaultOrganization) StringListFilter(org.opencastproject.index.service.resources.list.query.StringListFilter) Test(org.junit.Test)

Example 2 with ListProviderException

use of org.opencastproject.index.service.exception.ListProviderException in project opencast by opencast.

the class EmailListProvider method getList.

@Override
public Map<String, String> getList(String listName, ResourceListQuery query, Organization organization) throws ListProviderException {
    Map<String, String> result = new HashMap<String, String>();
    if (getListNameFromFilter(EmailFilterList.TEMPLATE_NAMES).equals(listName)) {
        String nameText = null;
        if (query.hasFilter(NAME) && query.getFilter(NAME).getValue().isSome() && query.getFilter(NAME).getValue().get() instanceof String) {
            nameText = (String) query.getFilter(NAME).getValue().get();
        }
        String startsWithText = null;
        if (query.hasFilter(STARTS_WITH_TEXT) && query.getFilter(STARTS_WITH_TEXT).getValue().isSome() && query.getFilter(STARTS_WITH_TEXT).getValue().get() instanceof String) {
            startsWithText = (String) query.getFilter(STARTS_WITH_TEXT).getValue().get();
        }
        List<MessageTemplate> messageTemplateList;
        try {
            if (nameText != null) {
                logger.debug("Searching for a template with name '{}'", nameText);
                messageTemplateList = mailService.getMessageTemplateByName(nameText);
            } else if (startsWithText != null) {
                logger.debug("Searching for templates that start with '{}'", startsWithText);
                messageTemplateList = mailService.getMessageTemplatesStartingWith(startsWithText);
            } else {
                logger.debug("Getting all templates");
                messageTemplateList = mailService.getMessageTemplates();
            }
        } catch (MailServiceException e) {
            logger.error("Error retreiving message templates from mail service: {}", ExceptionUtils.getStackTrace(e));
            throw new ListProviderException("Error retreiving message templates from mail service", e);
        }
        for (MessageTemplate messageTemplate : messageTemplateList) {
            result.put(Long.toString(messageTemplate.getId()), messageTemplate.getName());
        }
    } else {
        logger.warn("No email list for list name {} found", listName);
        throw new ListProviderException("No email list for list name " + listName + " found!");
    }
    return ListProviderUtil.filterMap(result, query);
}
Also used : MessageTemplate(org.opencastproject.messages.MessageTemplate) HashMap(java.util.HashMap) ListProviderException(org.opencastproject.index.service.exception.ListProviderException) MailServiceException(org.opencastproject.messages.MailServiceException)

Example 3 with ListProviderException

use of org.opencastproject.index.service.exception.ListProviderException in project opencast by opencast.

the class SeriesListProvider method getList.

@Override
public Map<String, String> getList(String listName, ResourceListQuery query, Organization organization) throws ListProviderException {
    Map<String, String> series = new HashMap<String, String>();
    SeriesQuery q = new SeriesQuery().setCount(Integer.MAX_VALUE);
    if (query != null) {
        if (query.hasFilter(FILTER_TEXT)) {
            StringListFilter filter = (StringListFilter) query.getFilter(FILTER_TEXT);
            if (filter.getValue().isSome())
                q.setText(filter.getValue().get());
        }
        if (query.getLimit().isSome())
            q.setCount(query.getLimit().get());
        if (query.getOffset().isSome())
            q.setStartPage(query.getOffset().get());
    }
    List<DublinCoreCatalog> result = null;
    try {
        if (!CONTRIBUTORS.equals(listName) && !ORGANIZERS.equals(listName) && !TITLE_EXTENDED.equals(listName)) {
            return seriesService.getIdTitleMapOfAllSeries();
        }
        result = seriesService.getSeries(q).getCatalogList();
    } catch (SeriesException e) {
        throw new ListProviderException("Error appends on the series service: " + e);
    } catch (UnauthorizedException e) {
        throw new ListProviderException("Unauthorized access to series service: " + e);
    }
    for (DublinCoreCatalog dc : result) {
        if (CONTRIBUTORS.equals(listName)) {
            String contributor = dc.getFirst(DublinCore.PROPERTY_CONTRIBUTOR);
            if (StringUtils.isNotBlank(contributor))
                series.put(contributor, contributor);
        } else if (ORGANIZERS.equals(listName)) {
            String organizer = dc.getFirst(DublinCore.PROPERTY_CREATOR);
            if (StringUtils.isNotBlank(organizer))
                series.put(organizer, organizer);
        } else if (TITLE_EXTENDED.equals(listName)) {
            String created = dc.getFirst(DublinCoreCatalog.PROPERTY_CREATED);
            String organizer = dc.getFirst(DublinCore.PROPERTY_CREATOR);
            StringBuilder sb = new StringBuilder(dc.getFirst(DublinCoreCatalog.PROPERTY_TITLE));
            if (StringUtils.isNotBlank(created) && StringUtils.isNotBlank(organizer)) {
                List<String> extendedTitleData = new ArrayList<>();
                if (StringUtils.isNotBlank(created)) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(EncodingSchemeUtils.decodeDate(created));
                    extendedTitleData.add(Integer.toString(calendar.get(Calendar.YEAR)));
                }
                if (StringUtils.isNotBlank(organizer))
                    extendedTitleData.add(organizer);
                sb.append(" (").append(StringUtils.join(extendedTitleData, ", ")).append(")");
            }
            series.put(dc.getFirst(DublinCore.PROPERTY_IDENTIFIER), sb.toString());
        } else {
            series.put(dc.getFirst(DublinCore.PROPERTY_IDENTIFIER), dc.getFirst(DublinCoreCatalog.PROPERTY_TITLE));
        }
    }
    return series;
}
Also used : SeriesQuery(org.opencastproject.series.api.SeriesQuery) HashMap(java.util.HashMap) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) ListProviderException(org.opencastproject.index.service.exception.ListProviderException) SeriesException(org.opencastproject.series.api.SeriesException) UnauthorizedException(org.opencastproject.security.api.UnauthorizedException) DublinCoreCatalog(org.opencastproject.metadata.dublincore.DublinCoreCatalog) StringListFilter(org.opencastproject.index.service.resources.list.query.StringListFilter)

Example 4 with ListProviderException

use of org.opencastproject.index.service.exception.ListProviderException in project opencast by opencast.

the class ServicesListProvider method getList.

@Override
public Map<String, String> getList(String listName, ResourceListQuery query, Organization organization) throws ListProviderException {
    ServicesListQuery servicesQuery;
    try {
        servicesQuery = (ServicesListQuery) query;
    } catch (ClassCastException ex) {
        servicesQuery = new ServicesListQuery(query);
    }
    Map<String, String> result = new HashMap<String, String>();
    if (LIST_STATUS.equals(listName)) {
        for (ServiceState s : ServiceState.values()) {
            result.put(s.toString(), SERVICE_STATUS_FILTER_PREFIX + s.toString());
        }
        return result;
    }
    List<ServiceRegistration> serviceRegistrations;
    try {
        serviceRegistrations = serviceRegistry.getServiceRegistrations();
    } catch (ServiceRegistryException ex) {
        throw new ListProviderException("Failed to get service registrations.", ex);
    }
    for (ServiceRegistration serviceRegistration : serviceRegistrations) {
        if (servicesQuery.getHostname().isSome() && !StringUtils.equals(servicesQuery.getHostname().get(), serviceRegistration.getHost()))
            continue;
        if (servicesQuery.getActions().isSome() && servicesQuery.getActions().get() && serviceRegistration.getServiceState() == ServiceState.NORMAL)
            continue;
        result.put(serviceRegistration.getServiceType(), serviceRegistration.getServiceType());
    }
    if (servicesQuery.getLimit().isSome() || servicesQuery.getLimit().isSome()) {
        int limit = servicesQuery.getLimit().getOrElse(0);
        int offset = servicesQuery.getOffset().getOrElse(0);
        result = new SmartIterator(limit, offset).applyLimitAndOffset(result);
    }
    return result;
}
Also used : ServiceState(org.opencastproject.serviceregistry.api.ServiceState) SmartIterator(org.opencastproject.util.SmartIterator) HashMap(java.util.HashMap) ListProviderException(org.opencastproject.index.service.exception.ListProviderException) ServicesListQuery(org.opencastproject.index.service.resources.list.query.ServicesListQuery) ServiceRegistryException(org.opencastproject.serviceregistry.api.ServiceRegistryException) ServiceRegistration(org.opencastproject.serviceregistry.api.ServiceRegistration)

Example 5 with ListProviderException

use of org.opencastproject.index.service.exception.ListProviderException in project opencast by opencast.

the class ListProvidersEndpoint method getList.

@GET
@Path("{source}.json")
@Produces(MediaType.APPLICATION_JSON)
@RestQuery(name = "list", description = "Provides key-value list from the given source", pathParameters = { @RestParameter(name = "source", description = "The source for the key-value list", isRequired = true, type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The maximum number of items to return per page", isRequired = false, name = "limit", type = RestParameter.Type.INTEGER), @RestParameter(description = "The offset", isRequired = false, name = "offset", type = RestParameter.Type.INTEGER), @RestParameter(description = "Filters", isRequired = false, name = "filter", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "Returns the key-value list for the given source.", responseCode = HttpServletResponse.SC_OK) }, returnDescription = "")
public Response getList(@PathParam("source") final String source, @QueryParam("limit") final int limit, @QueryParam("filter") final String filter, @QueryParam("offset") final int offset, @Context HttpHeaders headers) {
    if (listProvidersService.hasProvider(source)) {
        ResourceListQueryImpl query = new ResourceListQueryImpl();
        query.setLimit(limit);
        query.setOffset(offset);
        addRequestFiltersToQuery(filter, query);
        Map<String, String> autocompleteList;
        try {
            autocompleteList = listProvidersService.getList(source, query, securityService.getOrganization(), false);
        } catch (ListProviderException e) {
            logger.error("Not able to get list from provider {}: {}", source, e);
            return SERVER_ERROR;
        }
        JSONObject jsonList;
        try {
            jsonList = generateJSONObject(autocompleteList);
        } catch (JsonCreationException e) {
            logger.error("Not able to generate resources list JSON from source {}: {}", source, e);
            return SERVER_ERROR;
        }
        return Response.ok(jsonList.toString()).build();
    }
    return NOT_FOUND;
}
Also used : EndpointUtil.generateJSONObject(org.opencastproject.adminui.endpoint.EndpointUtil.generateJSONObject) JSONObject(org.json.simple.JSONObject) ResourceListQueryImpl(org.opencastproject.index.service.resources.list.query.ResourceListQueryImpl) ListProviderException(org.opencastproject.index.service.exception.ListProviderException) JsonCreationException(org.opencastproject.adminui.exception.JsonCreationException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Aggregations

ListProviderException (org.opencastproject.index.service.exception.ListProviderException)11 HashMap (java.util.HashMap)7 ResourceListQueryImpl (org.opencastproject.index.service.resources.list.query.ResourceListQueryImpl)3 ArrayList (java.util.ArrayList)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 JSONObject (org.json.simple.JSONObject)2 EndpointUtil.generateJSONObject (org.opencastproject.adminui.endpoint.EndpointUtil.generateJSONObject)2 JsonCreationException (org.opencastproject.adminui.exception.JsonCreationException)2 ResourceListProvider (org.opencastproject.index.service.resources.list.api.ResourceListProvider)2 ResourceListQuery (org.opencastproject.index.service.resources.list.api.ResourceListQuery)2 StringListFilter (org.opencastproject.index.service.resources.list.query.StringListFilter)2 ServiceRegistryException (org.opencastproject.serviceregistry.api.ServiceRegistryException)2 RestQuery (org.opencastproject.util.doc.rest.RestQuery)2 JValue (com.entwinemedia.fn.data.json.JValue)1 SimpleSerializer (com.entwinemedia.fn.data.json.SimpleSerializer)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1