Example usage for org.apache.solr.client.solrj.beans DocumentObjectBinder DocumentObjectBinder

List of usage examples for org.apache.solr.client.solrj.beans DocumentObjectBinder DocumentObjectBinder

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj.beans DocumentObjectBinder DocumentObjectBinder.

Prototype

public DocumentObjectBinder() 

Source Link

Usage

From source file:alba.solr.searchcomponents.AlbaRequestHandler.java

License:Apache License

public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    // TODO Auto-generated method stub

    /* List<SearchComponent> components = new ArrayList<SearchComponent>();
            /*  w  ww .j a va 2  s  .c  o  m*/
    MySearchComponent msc = new MySearchComponent();
            
    ResponseBuilder rb = new ResponseBuilder(req, rsp, components);
            
    msc.process(rb);*/

    //rsp.add("hello", rb.rsp.getValues());

    req.getContext().put(Loader.FUNCTIONS, functions);

    Object params[] = new Object[2];

    params[0] = req;
    params[1] = rsp;

    // what if this method calls rsp.add( .. ) ????
    Object result = this.function.getMethod().invoke(this.function.getInstance(), params);

    if (Map.class.isAssignableFrom(result.getClass())) {
        // if we got a Map, just return it as-is
        rsp.add(this.sectionName, result);
    } else // if we got anything else, try to serialize it!
    if (List.class.isAssignableFrom(result.getClass())) {
        for (Object o : (List) result) {
            DocumentObjectBinder dob = new DocumentObjectBinder();
            SolrInputDocument sd = dob.toSolrInputDocument(o);
            SolrDocument dest = ClientUtils.toSolrDocument(sd);

            HashMap<Object, Object> nl = (HashMap<Object, Object>) dest.get("functionDescriptor");

            //rsp.add(nl.get("name").toString(), dest2);

            rsp.add(null, dest);
        }
    }
    if (StaticResource.class.isAssignableFrom(result.getClass())) {
        FilteredShowFileRequestHandler file = new FilteredShowFileRequestHandler();

        file.init(new NamedList()); //to initialize internal variables - but in this way it will NOT get the proper configuration from SolrConfig!

        ModifiableSolrParams solrParams = new ModifiableSolrParams(req.getParams());

        StaticResource resource = ((StaticResource) result);
        solrParams.set("file", resource.getName());
        //TODO Proper mapping here!!
        //solrParams.set("contentType", "text/xml;charset=utf-8");

        solrParams.set("contentType", resource.getContentType());
        req.setParams(solrParams);

        file.handleRequest(req, rsp);
        //   logger.error("returning the content of " + );
    } else {
        // unable to do any kind of serialization.. just add the result and let the ResponseWriter handle it
        rsp.add(null, result);
    }

}

From source file:at.pagu.soldockr.core.convert.MappingSolrConverterTest.java

License:Apache License

@Before
public void setUp() {
    mappingContext = new SimpleSolrMappingContext();
    mappingContext.setApplicationContext(applicationContextMock);

    Mockito.when(solrServerFactoryMock.getSolrServer()).thenReturn(solrServerMock);
    Mockito.when(solrServerMock.getBinder()).thenReturn(new DocumentObjectBinder());

    converter = new MappingSolrConverter(solrServerFactoryMock, mappingContext);
    converter.afterPropertiesSet();/*from   w  w  w. ja  v a2  s. com*/
}

From source file:au.org.ala.biocache.dao.SearchDAOImpl.java

License:Open Source License

/**
 * Perform grouped facet query./*from  ww  w. j  ava  2  s .c  o  m*/
 * <p>
 * facets is the list of grouped facets required
 * flimit restricts the number of groups returned
 * pageSize restricts the number of docs in each group returned
 * fl is the list of fields in the returned docs
 */
public List<GroupFacetResultDTO> searchGroupedFacets(SpatialSearchRequestParams searchParams) throws Exception {
    queryFormatUtils.formatSearchQuery(searchParams);
    String queryString = searchParams.getFormattedQuery();
    searchParams.setFacet(false);

    //get facet group counts
    SolrQuery query = initSolrQuery(searchParams, false, null);
    query.setQuery(queryString);
    query.setFields(null);
    //now use the supplied facets to add groups to the query
    query.add("group", "true");
    query.add("group.ngroups", "true");
    query.add("group.limit", String.valueOf(searchParams.getPageSize()));
    query.setRows(searchParams.getFlimit());
    query.setFields(searchParams.getFl());
    for (String facet : searchParams.getFacets()) {
        query.add("group.field", facet);
    }
    QueryResponse response = runSolrQuery(query, searchParams);
    GroupResponse groupResponse = response.getGroupResponse();

    List<GroupFacetResultDTO> output = new ArrayList();
    for (GroupCommand gc : groupResponse.getValues()) {
        List<GroupFieldResultDTO> list = new ArrayList<GroupFieldResultDTO>();

        String facet = gc.getName();
        for (Group v : gc.getValues()) {
            List<OccurrenceIndex> docs = (new DocumentObjectBinder()).getBeans(OccurrenceIndex.class,
                    v.getResult());

            //build facet displayName and fq
            String value = v.getGroupValue();
            Long count = v.getResult() != null ? v.getResult().getNumFound() : 0L;
            if (value == null) {
                list.add(new GroupFieldResultDTO("", count, "-" + facet + ":*", docs));
            } else {
                list.add(new GroupFieldResultDTO(getFacetValueDisplayName(facet, value), count,
                        facet + ":\"" + value + "\"", docs));
            }
        }

        output.add(new GroupFacetResultDTO(gc.getName(), list, gc.getNGroups()));
    }

    return output;
}

From source file:com.frank.search.solr.core.convert.SolrJConverter.java

License:Apache License

private void initializeConverters() {
    if (!canConvert(Update.class, SolrInputDocument.class)) {
        getConversionService().addConverter(new SolrjConverters.UpdateToSolrInputDocumentConverter());
    }/*from  w w  w .  ja v a2  s .c  o  m*/
    if (!canConvert(Object.class, SolrInputDocument.class)) {
        getConversionService().addConverter(
                new SolrjConverters.ObjectToSolrInputDocumentConverter(new DocumentObjectBinder()));
    }
}

From source file:edu.unc.lib.dl.data.ingest.solr.test.AtomicUpdateTest.java

License:Apache License

@Test
public void atomicUpdate() throws IOException {
    IndexDocumentBean idb = new IndexDocumentBean();
    idb.setId("id");
    idb.setStatus(Arrays.asList("Unpublished", "Parent Unpublished"));

    DocumentObjectBinder binder = new DocumentObjectBinder();
    SolrInputDocument sid = binder.toSolrInputDocument(idb);

    String operation = "set";

    for (String fieldName : sid.getFieldNames()) {
        if (!ID_FIELD.equals(fieldName)) {
            SolrInputField inputField = sid.getField(fieldName);
            // Adding in each non-null field value, except the timestamp field which gets cleared if not specified so
            // that it always gets updated as part of a partial update
            // TODO enable timestamp updating when fix for SOLR-4133 is released, which enables setting null fields
            if (inputField != null && (inputField.getValue() != null || UPDATE_TIMESTAMP.equals(fieldName))) {
                Map<String, Object> partialUpdate = new HashMap<String, Object>();
                partialUpdate.put(operation, inputField.getValue());
                sid.setField(fieldName, partialUpdate);
            }/*from ww  w . ja v a 2s. c  o  m*/
        }
    }

    /*   Map<String,String> mapField = new HashMap<String,String>();
       mapField.put("", arg1)
       Map<String, Object> partialUpdate = new HashMap<String, Object>();
       partialUpdate.put("set", inputField.getFirstValue());
       sid.setField(fieldName, partialUpdate);*/

    StringWriter writer = new StringWriter();
    ClientUtils.writeXML(sid, writer);

    System.out.println(writer.toString());

    System.out.println(sid.toString());
}

From source file:edu.usu.sdl.openstorefront.service.SearchServiceImpl.java

License:Apache License

@Override
public List<ComponentSearchView> getSearchItems(SearchQuery query, FilterQueryParams filter) {
    // use for advanced search with And - Or combinations on separate fields
    String queryOperator = " " + SolrAndOr.OR + " ";
    String myQueryString;/*  ww  w.  j  a  v  a2  s  .co  m*/

    // If incoming query string is blank, default to solar *:* for the full query
    if (StringUtils.isNotBlank(query.getQuery())) {
        StringBuilder queryData = new StringBuilder();

        Field fields[] = SolrComponentModel.class.getDeclaredFields();
        for (Field field : fields) {
            org.apache.solr.client.solrj.beans.Field fieldAnnotation = field
                    .getAnnotation(org.apache.solr.client.solrj.beans.Field.class);
            if (fieldAnnotation != null && field.getType() == String.class) {
                String name = field.getName();
                if (StringUtils.isNotBlank(fieldAnnotation.value())
                        && org.apache.solr.client.solrj.beans.Field.DEFAULT
                                .equals(fieldAnnotation.value()) == false) {
                    name = fieldAnnotation.value();
                }

                queryData.append(SolrEquals.EQUAL.getSolrOperator()).append(name)
                        .append(SolrManager.SOLR_QUERY_SEPERATOR).append(query.getQuery())
                        .append(queryOperator);
            }
        }
        myQueryString = queryData.toString();
        if (myQueryString.endsWith(queryOperator)) {
            queryData.delete((myQueryString.length() - (queryOperator.length())), myQueryString.length());
            myQueryString = queryData.toString();
        }
    } else {
        myQueryString = SolrManager.SOLR_ALL_QUERY;
    }
    log.log(Level.FINER, myQueryString);

    // execute the searchComponent method and bring back from solr a list array
    List<SolrComponentModel> resultsList = new ArrayList<>();
    try {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery(myQueryString);

        // fields to be returned back from solr
        solrQuery.setFields(SolrComponentModel.ID_FIELD, SolrComponentModel.ISCOMPONENT_FIELD);
        solrQuery.setStart(filter.getOffset());
        solrQuery.setRows(filter.getMax());

        Field sortField = ReflectionUtil.getField(new SolrComponentModel(), filter.getSortField());
        if (sortField != null) {
            String sortFieldText = filter.getSortField();
            org.apache.solr.client.solrj.beans.Field fieldAnnotation = sortField
                    .getAnnotation(org.apache.solr.client.solrj.beans.Field.class);
            if (fieldAnnotation != null) {
                sortFieldText = fieldAnnotation.value();
            }
            SolrQuery.ORDER order = SolrQuery.ORDER.desc;
            if (OpenStorefrontConstant.SORT_ASCENDING.equalsIgnoreCase(filter.getSortOrder())) {
                order = SolrQuery.ORDER.asc;
            }
            solrQuery.addSort(sortFieldText, order);
        }

        solrQuery.setIncludeScore(true);

        QueryResponse response = SolrManager.getServer().query(solrQuery);
        SolrDocumentList results = response.getResults();
        DocumentObjectBinder binder = new DocumentObjectBinder();
        resultsList = binder.getBeans(SolrComponentModel.class, results);
    } catch (SolrServerException ex) {
        throw new OpenStorefrontRuntimeException("Search Failed",
                "Contact System Admin.  Seach server maybe Unavailable", ex);
    } catch (Exception ex) {
        log.log(Level.WARNING, "Solr query failed unexpectly; likely bad input.", ex);
    }

    //Pulling the full object on the return
    List<ComponentSearchView> views = new ArrayList<>();

    List<String> componentIds = new ArrayList<>();
    for (SolrComponentModel result : resultsList) {
        if (result.getIsComponent()) {
            componentIds.add(result.getId());
        }
    }

    //remove bad indexes, if any
    List<ComponentSearchView> componentSearchViews = getComponentService().getSearchComponentList(componentIds);
    Set<String> goodComponentIdSet = new HashSet<>();
    for (ComponentSearchView view : componentSearchViews) {
        goodComponentIdSet.add(view.getComponentId());
    }

    for (String componentId : componentIds) {
        if (goodComponentIdSet.contains(componentId) == false) {
            log.log(Level.FINE, MessageFormat.format("Removing bad index: {0}", componentId));
            deleteById(componentId);
        }
    }
    views.addAll(componentSearchViews);

    List<ComponentSearchView> articleViews = getAttributeService().getArticlesSearchView();
    Map<String, ComponentSearchView> allViews = new HashMap<>();
    for (ComponentSearchView componentSearchView : articleViews) {
        AttributeCodePk attributeCodePk = new AttributeCodePk();
        attributeCodePk.setAttributeType(componentSearchView.getArticleAttributeType());
        attributeCodePk.setAttributeCode(componentSearchView.getArticleAttributeCode());
        allViews.put(attributeCodePk.toKey(), componentSearchView);
    }
    for (SolrComponentModel result : resultsList) {

        if (result.getIsComponent() == false) {
            ComponentSearchView view = allViews.get(result.getId());
            if (view != null) {
                views.add(view);
            } else {
                log.log(Level.FINE, MessageFormat.format("Removing bad index: {0}", result.getId()));
                deleteById(result.getId());
            }
        }
    }

    //TODO: Get the score and sort by score
    return views;
}

From source file:org.dataone.cn.solr.client.solrj.MockSolrServer.java

License:Apache License

@Override
public DocumentObjectBinder getBinder() {
    if (binder == null) {
        binder = new DocumentObjectBinder();
    }
    return binder;
}