org.apache.cxf.jaxrs.ext.search.SearchContext Java Examples

The following examples show how to use org.apache.cxf.jaxrs.ext.search.SearchContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BookStore.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/books/{search}/chapter/{chapter}")
@Produces("application/xml")
public Chapter getChapterFromSelectedBook(@Context SearchContext searchContext,
                                          @PathParam("search") String expression,
                                          @PathParam("chapter") int chapter) {

    SearchCondition<Book> sc = searchContext.getCondition(expression, Book.class);
    if (sc == null) {
        throw new WebApplicationException(404);
    }
    List<Book> found = sc.findAll(books.values());
    if (found.size() != 1) {
        throw new WebApplicationException(404);
    }
    Book selectedBook = found.get(0);

    return selectedBook.getChapter(chapter);
}
 
Example #2
Source File: BookStore.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/books/search")
@Produces("application/xml")
public Book getBook(@Context SearchContext searchContext)
    throws BookNotFoundFault {

    SearchCondition<Book> sc = searchContext.getCondition(Book.class);
    if (sc == null) {
        throw new BookNotFoundFault("Search exception");
    }
    List<Book> found = sc.findAll(books.values());
    if (found.size() != 1) {
        throw new BookNotFoundFault("Single book is expected");
    }
    return found.get(0);
}
 
Example #3
Source File: IdentityProvidersApi.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
@Valid
@GET
@Path("/templates")

@Produces({ "application/json" })
@ApiOperation(value = "List identity provider templates ", notes = "This API provides the list of available identity provider templates. ", response = IdentityProviderTemplateListResponse.class, authorizations = {
    @Authorization(value = "BasicAuth"),
    @Authorization(value = "OAuth2", scopes = {
        
    })
}, tags={ "Template management", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "Successful response", response = IdentityProviderTemplateListResponse.class),
    @ApiResponse(code = 400, message = "Bad Request", response = Error.class),
    @ApiResponse(code = 401, message = "Unauthorized", response = Void.class),
    @ApiResponse(code = 403, message = "Forbidden", response = Void.class),
    @ApiResponse(code = 404, message = "Not Found", response = Error.class),
    @ApiResponse(code = 500, message = "Server Error", response = Error.class)
})
public Response getIDPTemplates(    @Valid@ApiParam(value = "Maximum number of records to return. ")  @QueryParam
        ("limit") Integer limit,     @Valid@ApiParam(value = "Number of records to skip for pagination. ")
@QueryParam("offset") Integer offset, @Context SearchContext searchContext) {

    return delegate.getIDPTemplates(limit,  offset, searchContext );
}
 
Example #4
Source File: ServerApplicationManagementService.java    From identity-api-server with Apache License 2.0 6 votes vote down vote up
/**
 * List all the application templates of the tenant.
 *
 * @param limit  maximum number of items to be returned.
 * @param offset number of records to skip for pagination.
 * @return ApplicationTemplatesList containing the list of templates.
 */
public ApplicationTemplatesList listApplicationTemplates(Integer limit, Integer offset, SearchContext
        searchContext) {

    validatePaginationSupport(limit, offset);
    try {
        List<Template> templateList = getTemplateManager().listTemplates(TemplateMgtConstants.TemplateType
                .APPLICATION_TEMPLATE.toString(), null, null, getSearchCondition
                (TemplateMgtConstants.TemplateType.APPLICATION_TEMPLATE.toString(), ContextLoader
                        .getTenantDomainFromContext(), searchContext));
        List<ApplicationTemplatesListItem> applicationTemplateList = templateList.stream().map(new
                TemplateToApplicationTemplateListItem()).collect(Collectors.toList());

        ApplicationTemplatesList applicationTemplates = new ApplicationTemplatesList();
        applicationTemplates.setTemplates(applicationTemplateList);
        return applicationTemplates;
    } catch (TemplateManagementException e) {
        throw handleTemplateManagementException(e, "Error while listing application templates.");
    }
}
 
Example #5
Source File: SearchApi.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@GET

 @Consumes({ "application/json" })
 @Produces({ "application/json" })
 @io.swagger.annotations.ApiOperation(value = "Retrieve tenant resources based on search parameters\n", notes = "This API is used to search resources across tenants based on search parameters given in the search query. For more information on using this API, see [Retrieving Tenant Resources Based on Search Parameters](https://docs.wso2.com/display/identity-server/Retrieving+Tenant+Resources+Based+on+Search+Parameters).\n", response = ResourcesDTO.class)
 @io.swagger.annotations.ApiResponses(value = {
         @io.swagger.annotations.ApiResponse(code = 200, message = "Ok"),

         @io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request"),

         @io.swagger.annotations.ApiResponse(code = 401, message = "Unauthorized"),

         @io.swagger.annotations.ApiResponse(code = 500, message = "Server Error") })

 public Response searchGet(@Context SearchContext searchContext)
 {
  return delegate.searchGet(searchContext);
 }
 
Example #6
Source File: SearchApiServiceImpl.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private Condition getSearchCondition(SearchContext searchContext)
        throws SearchConditionException {

    if (searchContext != null) {
        SearchCondition<ResourceSearchBean> searchCondition = searchContext.getCondition(ResourceSearchBean.class);
        if (searchCondition != null) {
            return buildSearchCondition(searchCondition);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Search condition parsed from the search expression is invalid.");
            }
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Cannot find a valid search context.");
        }
    }
    throw new SearchConditionException("Invalid search expression found.");
}
 
Example #7
Source File: BookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/books[{search}]/chapter")
@Produces("application/xml")
public Chapter getIntroChapterFromSelectedBook2(@Context SearchContext searchContext,
                                               @PathParam("search") String expression) {

    return getChapterFromSelectedBook(searchContext, expression, 1);
}
 
Example #8
Source File: BookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/books({search})/chapter")
@Produces("application/xml")
public Chapter getIntroChapterFromSelectedBook(@Context SearchContext searchContext,
                                               @PathParam("search") String expression) {

    return getChapterFromSelectedBook(searchContext, expression, 1);
}
 
Example #9
Source File: BookCatalog.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public Collection<ScoreDoc> findBook(@Context SearchContext searchContext) throws IOException {
    try (IndexReader reader = DirectoryReader.open(directory)) {
        IndexSearcher searcher = new IndexSearcher(reader);
        visitor.visit(searchContext.getCondition(SearchBean.class));
        return Arrays.asList(searcher.search(visitor.getQuery(), 1000).scoreDocs);
    }
}
 
Example #10
Source File: ApplicationsApi.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
@Valid
@GET
@Path("/templates")

@Produces({ "application/json" })
@ApiOperation(value = "List Application Templates ", notes = "This API provides the capability to retrieve the list of templates available. ", response = ApplicationTemplatesList.class, authorizations = {
    @Authorization(value = "BasicAuth"),
    @Authorization(value = "OAuth2", scopes = {
        
    })
}, tags={ "Application Templates", })
@ApiResponses(value = { 
    @ApiResponse(code = 200, message = "OK", response = ApplicationTemplatesList.class),
    @ApiResponse(code = 400, message = "Bad Request", response = Error.class),
    @ApiResponse(code = 401, message = "Unauthorized", response = Void.class),
    @ApiResponse(code = 403, message = "Forbidden", response = Void.class),
    @ApiResponse(code = 404, message = "Not Found", response = Error.class),
    @ApiResponse(code = 500, message = "Server Error", response = Error.class),
    @ApiResponse(code = 501, message = "Not Implemented", response = Error.class)
})
public Response getAllApplicationTemplates(    @Valid@ApiParam(value = "Maximum number of records to return. ")
                                                   @QueryParam("limit") Integer limit,     @Valid@ApiParam(value
        = "Number of records to skip for pagination. ")  @QueryParam("offset") Integer offset, @Context
        SearchContext searchContext) {

    return delegate.getAllApplicationTemplates(limit,  offset, searchContext );
}
 
Example #11
Source File: ServerApplicationManagementService.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve search condition from @{SearchContext}.
 *
 * @param templateType  Template type.
 * @param tenantDomain  Tenant domain.
 * @param searchContext Search context.
 * @return  Condition.
 */
private Condition getSearchCondition(String templateType, String tenantDomain, SearchContext searchContext) {

    if (searchContext != null) {
        SearchCondition<ResourceSearchBean> searchCondition = searchContext.getCondition(ResourceSearchBean.class);
        if (searchCondition != null) {
            Condition result = buildSearchCondition(searchCondition);
            List<Condition> list = new ArrayList<>();
            Condition typeCondition = new PrimitiveCondition(ApplicationManagementConstants.TemplateProperties
                    .TEMPLATE_TYPE_KEY, EQUALS, templateType);
            Condition tenantCondition = new PrimitiveCondition(ApplicationManagementConstants.TemplateProperties
                    .TENANT_DOMAIN_KEY, EQUALS, tenantDomain);
            if (result instanceof ComplexCondition) {
                list = ((ComplexCondition) result).getConditions();
                list.add(typeCondition);
                list.add(tenantCondition);
            } else if (result instanceof PrimitiveCondition) {
                list.add(result);
                list.add(typeCondition);
                list.add(tenantCondition);
            }
            return new ComplexCondition(getComplexOperatorFromOdata(ConditionType.AND),
                    list);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Search condition parsed from the search expression is invalid.");
            }
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Cannot find a valid search context.");
        }
    }
    return null;
}
 
Example #12
Source File: ServerIdpManagementService.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve search condition from @{SearchContext}.
 *
 * @param templateType  Template type.
 * @param tenantDomain  Tenant domain.
 * @param searchContext Search context.
 * @return  Condition.
 */
private Condition getSearchCondition(String templateType, String tenantDomain, SearchContext searchContext) {

    if (searchContext != null) {
        SearchCondition<ResourceSearchBean> searchCondition = searchContext.getCondition(ResourceSearchBean.class);
        if (searchCondition != null) {
            Condition result = buildSearchCondition(searchCondition);
            Condition typeCondition = new PrimitiveCondition(Constants.TEMPLATE_TYPE_KEY, EQUALS, templateType);
            Condition tenantCondition = new PrimitiveCondition(Constants.TENANT_DOMAIN_KEY, EQUALS, tenantDomain);

            List<Condition> list = new ArrayList<>();
            list.add(result);
            list.add(typeCondition);
            list.add(tenantCondition);
            return new ComplexCondition(getComplexOperatorFromOdata(ConditionType.AND),
                    list);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Search condition parsed from the search expression is invalid.");
            }
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Cannot find a valid search context.");
        }
    }
    return null;
}
 
Example #13
Source File: ServerIdpManagementService.java    From identity-api-server with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve the list of IDP templates.
 *
 * @param limit         Items per page.
 * @param offset        Offset.
 * @param searchContext Search Criteria. E.g. filter="name" sw "google" and "category" eq "DEFAULT"
 * @return List of identity templates.
 */
public IdentityProviderTemplateListResponse getIDPTemplates(Integer limit, Integer offset, SearchContext
        searchContext) {

    try {
        TemplateManager templateManager = IdentityProviderServiceHolder.getTemplateManager();
        List<Template> templateList = templateManager.listTemplates(
                TemplateMgtConstants.TemplateType.IDP_TEMPLATE.toString(), limit, offset, getSearchCondition
                        (TemplateMgtConstants.TemplateType.IDP_TEMPLATE.toString(), ContextLoader
                                .getTenantDomainFromContext(), searchContext));
        return createIDPTemplateListResponse(templateList, offset, limit, searchContext.getSearchExpression());
    } catch (TemplateManagementException e) {
        throw handleTemplateMgtException(e, Constants.ErrorMessage.ERROR_CODE_ERROR_LISTING_IDP_TEMPLATES, null);
    }
}
 
Example #14
Source File: AnyObjectServiceTest.java    From syncope with Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void setup() {
    if (SERVER == null) {
        AnyObjectDAO anyObjectDAO = mock(AnyObjectDAO.class);

        AnyObjectLogic logic = mock(AnyObjectLogic.class);
        when(logic.search(any(SearchCond.class), anyInt(), anyInt(), anyList(), anyString(), anyBoolean())).
                thenAnswer(ic -> {
                    AnyObjectTO printer1 = new AnyObjectTO();
                    printer1.setKey(UUID.randomUUID().toString());
                    printer1.setName("printer1");
                    printer1.setType("PRINTER");
                    printer1.getPlainAttrs().add(new Attr.Builder("location").value("here").build());

                    AnyObjectTO printer2 = new AnyObjectTO();
                    printer2.setKey(UUID.randomUUID().toString());
                    printer2.setName("printer2");
                    printer2.setType("PRINTER");
                    printer2.getPlainAttrs().add(new Attr.Builder("location").value("there").build());

                    return Pair.of(2, Arrays.asList(printer1, printer2));
                });
        when(logic.create(any(AnyObjectCR.class), anyBoolean())).thenAnswer(ic -> {
            AnyObjectTO anyObjectTO = new AnyObjectTO();
            EntityTOUtils.toAnyTO(ic.getArgument(0), anyObjectTO);
            anyObjectTO.setKey(UUID.randomUUID().toString());

            ProvisioningResult<AnyObjectTO> result = new ProvisioningResult<>();
            result.setEntity(anyObjectTO);
            return result;
        });

        SearchCondVisitor searchCondVisitor = mock(SearchCondVisitor.class);
        when(searchCondVisitor.getQuery()).thenReturn(new SearchCond());

        @SuppressWarnings("unchecked")
        SearchCondition<SearchBean> sc = mock(SearchCondition.class);
        doNothing().when(sc).accept(any());
        SearchContext searchContext = mock(SearchContext.class);
        when(searchContext.getCondition(anyString(), eq(SearchBean.class))).thenReturn(sc);

        UriInfo uriInfo = mock(UriInfo.class);
        when(uriInfo.getAbsolutePathBuilder()).thenReturn(new UriBuilderImpl());
        when(uriInfo.getQueryParameters()).thenReturn(new MetadataMap<>());

        MessageContext messageContext = mock(MessageContext.class);
        MockHttpServletRequest httpRequest = new MockHttpServletRequest();
        httpRequest.addHeader(RESTHeaders.NULL_PRIORITY_ASYNC, "false");
        when(messageContext.getHttpServletRequest()).thenReturn(httpRequest);
        when(messageContext.getHttpServletResponse()).thenReturn(new MockHttpServletResponse());

        Request request = mock(Request.class);
        when(request.evaluatePreconditions(any(Date.class))).thenReturn(Response.notModified());
        when(messageContext.getRequest()).thenReturn(request);

        AnyObjectServiceImpl service = new AnyObjectServiceImpl();
        ReflectionTestUtils.setField(service, "anyObjectDAO", anyObjectDAO);
        ReflectionTestUtils.setField(service, "logic", logic);
        ReflectionTestUtils.setField(service, "searchCondVisitor", searchCondVisitor);
        ReflectionTestUtils.setField(service, "searchContext", searchContext);
        ReflectionTestUtils.setField(service, "uriInfo", uriInfo);
        ReflectionTestUtils.setField(service, "messageContext", messageContext);

        JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
        sf.setAddress(LOCAL_ADDRESS);
        sf.setResourceClasses(AnyObjectService.class);
        sf.setResourceProvider(
                AnyObjectService.class,
                new SingletonResourceProvider(service, true));

        sf.setInInterceptors(Arrays.asList(gzipInInterceptor, validationInInterceptor));
        sf.setOutInterceptors(Arrays.asList(gzipOutInterceptor));

        sf.setProviders(Arrays.asList(dateParamConverterProvider, jsonProvider, xmlProvider, yamlProvider,
                exceptionMapper, searchContextProvider, addETagFilter));

        SERVER = sf.create();
    }

    assertNotNull(SERVER);
}
 
Example #15
Source File: Catalog.java    From cxf with Apache License 2.0 4 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@CrossOriginResourceSharing(allowAllOrigins = true)
@Path("/search")
public Response findBook(@Context SearchContext searchContext,
        @Context final UriInfo uri) throws IOException {

    final IndexReader reader = DirectoryReader.open(directory);
    final IndexSearcher searcher = new IndexSearcher(reader);
    final JsonArrayBuilder builder = Json.createArrayBuilder();

    try {
        visitor.reset();
        visitor.visit(searchContext.getCondition(SearchBean.class));

        final Query query = visitor.getQuery();
        if (query != null) {
            final TopDocs topDocs = searcher.search(query, 1000);
            for (final ScoreDoc scoreDoc: topDocs.scoreDocs) {
                final Document document = reader.document(scoreDoc.doc);
                final String source = document
                    .getField(LuceneDocumentMetadata.SOURCE_FIELD)
                    .stringValue();

                builder.add(
                    Json.createObjectBuilder()
                        .add("source", source)
                        .add("score", scoreDoc.score)
                        .add("url", uri.getBaseUriBuilder()
                                .path(Catalog.class)
                                .path(source)
                                .build().toString())
                );
            }
        }

        return Response.ok(builder.build()).build();
    } finally {
        reader.close();
    }
}
 
Example #16
Source File: UserServiceImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Override
public User searchUser(@PathParam("query") String query, @Context SearchContext searchContext)
    throws UserNotFoundFault {

    SearchCondition<User> sc = searchContext.getCondition(query, User.class);
    if (sc == null) {
        throw new UserNotFoundFault("Search exception");
    }

    LdapQueryVisitor<User> visitor =
        new LdapQueryVisitor<>(Collections.singletonMap("name", "cn"));
    visitor.setEncodeQueryValues(encodeQueryValues);
    sc.accept(visitor.visitor());
    String parsedQuery = visitor.getQuery();

    ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("ldap-jaxrsport.xml");
    LdapTemplate template = (LdapTemplate)appContext.getBean("ldapTemplate");

    String userBaseDn = "OU=users,DC=example,DC=com";
    String[] attributes = new String[] {"sn", "cn"};
    Map<String, Attribute> attrs =
        getAttributesOfEntry(template, userBaseDn, "person", parsedQuery, attributes);

    appContext.close();

    if (attrs == null || attrs.isEmpty()) {
        throw new UserNotFoundFault("Search exception");
    }
    User user = new User();
    try {
        for (Entry<String, Attribute> result : attrs.entrySet()) {
            if ("sn".equals(result.getKey())) {
                user.setSurname((String)result.getValue().get());
            } else if ("cn".equals(result.getKey())) {
                user.setName((String)result.getValue().get());
            }
        }
    } catch (NamingException e) {
        throw new UserNotFoundFault("Search exception");
    }

    return user;
}
 
Example #17
Source File: UserService.java    From cxf with Apache License 2.0 4 votes vote down vote up
@GET
@Path("/search/{query}")
@Produces("application/xml")
User searchUser(@PathParam("query") String query,
                @Context SearchContext searchContext) throws UserNotFoundFault;
 
Example #18
Source File: ApplicationsApiServiceImpl.java    From identity-api-server with Apache License 2.0 4 votes vote down vote up
@Override
public Response getAllApplicationTemplates(Integer limit, Integer offset, SearchContext searchContext) {

    return Response.ok().entity(applicationManagementService.listApplicationTemplates(limit, offset,
            searchContext)).build();
}
 
Example #19
Source File: IdentityProvidersApiServiceImpl.java    From identity-api-server with Apache License 2.0 4 votes vote down vote up
@Override
public Response getIDPTemplates(Integer limit, Integer offset, SearchContext searchContext) {

    return Response.ok().entity(idpManagementService.getIDPTemplates(limit, offset, searchContext)).build();
}
 
Example #20
Source File: ApplicationsApiService.java    From identity-api-server with Apache License 2.0 votes vote down vote up
public Response getAllApplicationTemplates(Integer limit, Integer offset, SearchContext searchContext); 
Example #21
Source File: SearchApiService.java    From carbon-identity-framework with Apache License 2.0 votes vote down vote up
public abstract Response searchGet(SearchContext searchContext); 
Example #22
Source File: IdentityProvidersApiService.java    From identity-api-server with Apache License 2.0 votes vote down vote up
public Response getIDPTemplates(Integer limit, Integer offset, SearchContext searchContext);