Example usage for org.apache.solr.common.util NamedList iterator

List of usage examples for org.apache.solr.common.util NamedList iterator

Introduction

In this page you can find the example usage for org.apache.solr.common.util NamedList iterator.

Prototype

@Override
public Iterator<Map.Entry<String, T>> iterator() 

Source Link

Document

Support the Iterable interface

Usage

From source file:com.doculibre.constellio.servlets.SolrJExampleMain.java

License:Open Source License

/**
 * Print documents and facets/* www  .j a va2 s . c om*/
 * 
 * @param response
 */
@SuppressWarnings("unchecked")
public static void print(QueryResponse response) {
    SolrDocumentList docs = response.getResults();
    if (docs != null) {
        System.out.println(docs.getNumFound() + " documents found, " + docs.size() + " returned : ");
        for (int i = 0; i < docs.size(); i++) {
            SolrDocument doc = docs.get(i);
            System.out.println("\t" + doc.toString());
        }
    }

    List<FacetField> fieldFacets = response.getFacetFields();
    if (fieldFacets != null && fieldFacets.isEmpty()) {
        System.out.println("\nField Facets : ");
        for (FacetField fieldFacet : fieldFacets) {
            System.out.print("\t" + fieldFacet.getName() + " :\t");
            if (fieldFacet.getValueCount() > 0) {
                for (Count count : fieldFacet.getValues()) {
                    System.out.print(count.getName() + "[" + count.getCount() + "]\t");
                }
            }
            System.out.println("");
        }
    }

    Map<String, Integer> queryFacets = response.getFacetQuery();
    if (queryFacets != null && !queryFacets.isEmpty()) {
        System.out.println("\nQuery facets : ");
        for (String queryFacet : queryFacets.keySet()) {
            System.out.println("\t" + queryFacet + "\t[" + queryFacets.get(queryFacet) + "]");
        }
        System.out.println("");
    }

    NamedList<NamedList<Object>> spellCheckResponse = (NamedList<NamedList<Object>>) response.getResponse()
            .get("spellcheck");

    if (spellCheckResponse != null) {
        Iterator<Entry<String, NamedList<Object>>> wordsIterator = spellCheckResponse.iterator();

        while (wordsIterator.hasNext()) {
            Entry<String, NamedList<Object>> entry = wordsIterator.next();
            String word = entry.getKey();
            NamedList<Object> spellCheckWordResponse = entry.getValue();
            boolean correct = spellCheckWordResponse.get("frequency").equals(1);
            System.out.println("Word: " + word + ",\tCorrect?: " + correct);
            NamedList<Integer> suggestions = (NamedList<Integer>) spellCheckWordResponse.get("suggestions");
            if (suggestions != null && suggestions.size() > 0) {
                System.out.println("Suggestions : ");
                Iterator<Entry<String, Integer>> suggestionsIterator = suggestions.iterator();
                while (suggestionsIterator.hasNext()) {
                    System.out.println("\t" + suggestionsIterator.next().getKey());
                }

            }
            System.out.println("");
        }

    }

}

From source file:com.doculibre.constellio.utils.NamedListUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
private static Element newNamedListElement(NamedList<Object> nl) {
    Element nlElement = new Element("lst");
    Iterator<Map.Entry<String, Object>> entries = nl.iterator();
    while (entries.hasNext()) {
        Map.Entry<String, Object> entry = entries.next();
        if (entry.getValue() != null) {
            if ("attr".equals(entry.getKey().toLowerCase())) {
                NamedList<Object> attributes = (NamedList<Object>) entry.getValue();
                for (Map.Entry<String, Object> attribute : attributes) {
                    // We want the name to be the first attribute (for
                    // Junit)
                    nlElement.setAttribute("name", "");
                    Element child = toElement(attribute.getValue());
                    if (child != null) {
                        nlElement.setAttribute(attribute.getKey(), child.getText());
                    }//from  www .j a v  a 2  s.  c  om
                }
            } else {
                Element child = toElement(entry.getValue());
                if (child != null) {
                    nameElement(child, entry.getKey());
                    nlElement.addContent(child);
                }
            }

        }
    }
    return nlElement;
}

From source file:com.doculibre.constellio.utils.NamedListUtilsTest.java

License:Open Source License

/**
 * convert an XML file to a NamedList and convert it back to a XML document.
 * Important : These documents are converted in SolrDocument, it does not
 * test the conversion of document represented by a NamedList,
 *//*from   w  w w.  ja  v a2  s. com*/
@Test
public void testConversions() throws IOException {

    File f = new File(NamedListUtilsTest.class.getResource("ANamedList.xml").getFile());

    String initialXML = readFileAsString(f);

    NamedList<Object> nl = NamedListUtils.convertXMLToNamedList(new FileInputStream(f));
    TestCase.assertEquals(3, nl.size());
    Iterator<Map.Entry<String, Object>> keys = nl.iterator();
    TestCase.assertEquals(ServletsConstants.RESPONSE_HEADER, keys.next().getKey());
    TestCase.assertEquals(ServletsConstants.RESPONSE, keys.next().getKey());
    File tempFile = File.createTempFile("temp", ".xml");

    NamedListUtils.convertResponseNamedListToXML(nl, new FileOutputStream(tempFile));
    String xml = readFileAsString(tempFile);

    System.out.println(xml);
    TestCase.assertEquals(initialXML.replaceAll("  ", "").replace("\n", ""),
            xml.replaceAll("  ", "").replace("\n", "").replace("\r", ""));

}

From source file:com.doculibre.constellio.wicket.panels.search.advanced.searchRulePanels.TextSearchRulePanel.java

License:Open Source License

public TextSearchRulePanel(String id, SimpleSearch search, TextSearchRule rule, IModel typesModel) {
    super(id, search, rule, typesModel);

    TextField valueTextField;//from www  . j a  va  2s  . c om
    if (enabledRuleModel.getObject() != null
            && ((AdvancedSearchEnabledRule) enabledRuleModel.getObject()).getIndexField().isAutocompleted()) {
        IModel valueModel = new Model(rule.getTextValue());
        AutoCompleteSettings settings = new AutoCompleteSettings();
        settings.setCssClassName("autoCompleteChoices");

        final String collectionName = search.getCollectionName();
        final String indexfieldName = rule.getIndexFieldName();
        valueTextField = new TextAndValueAutoCompleteTextField<Map.Entry<String, Object>>("value", valueModel,
                String.class, settings) {

            @Override
            protected Iterator<Map.Entry<String, Object>> getChoicesForWord(String word) {
                RecordCollectionServices recordCollectionServices = ConstellioSpringUtils
                        .getRecordCollectionServices();
                RecordCollection collection = recordCollectionServices.get(collectionName);
                IndexField indexField = collection.getIndexField(indexfieldName);
                AutocompleteServices autocompleteServices = ConstellioSpringUtils.getAutocompleteServices();
                NamedList<Object> choices = autocompleteServices.suggest(word, indexField);
                return choices.iterator();
            }

        };
    } else {
        valueTextField = new TextField("value", new Model(rule.getTextValue()));

    }

    valueTextField.add(new SimpleAttributeModifier("name",
            rule.getPrefix() + SearchRule.DELIM + TextSearchRule.PARAM_VALUE));
    add(valueTextField);

    DropDownChoice searchMethodSelect = new DropDownChoice("searchMethod", new Model(rule.getSearchMethod()),
            Arrays.asList(TextSearchMethod.values()), new IChoiceRenderer() {

                @Override
                public String getIdValue(Object object, int index) {
                    return ((TextSearchMethod) object).name();
                }

                @Override
                public Object getDisplayValue(Object object) {
                    return new StringResourceModel(((TextSearchMethod) object).name(), TextSearchRulePanel.this,
                            null).getString();
                }
            });
    searchMethodSelect.add(new SimpleAttributeModifier("name",
            rule.getPrefix() + SearchRule.DELIM + TextSearchRule.PARAM_SEARCH_METHOD));
    add(searchMethodSelect);
}

From source file:com.shaie.solr.solrj.AddReplicaResponse.java

License:Apache License

@SuppressWarnings("unchecked")
private String extractCoreName() {
    final NamedList<Object> successEntry = (NamedList<Object>) rawResponse.getResponse().get("success");
    final Entry<String, Object> coreEntry = successEntry.iterator().next();
    return (String) ((NamedList<Object>) coreEntry.getValue()).get("core");
}

From source file:net.yacy.document.content.SurrogateReader.java

License:Open Source License

@Override
public void run() {
    // test the syntax of the stream by reading parts of the beginning
    try {// ww  w.  ja v a2s.c  om
        if (isSolrDump()) {
            BufferedReader br = new BufferedReader(new InputStreamReader(this.inputStream, "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.startsWith("<doc>"))
                    continue;
                try {
                    NamedList<Object> nl = new XMLResponseParser()
                            .processResponse(new StringReader("<result>" + line + "</result>")); // 
                    SolrDocument doc = (SolrDocument) nl.iterator().next().getValue();

                    // check if url is in accepted domain
                    String u = (String) doc.getFieldValue("sku");
                    if (u != null) {
                        try {
                            DigestURL url = new DigestURL(u);
                            final String urlRejectReason = this.crawlStacker.urlInAcceptedDomain(url);
                            if (urlRejectReason == null) {
                                // convert DCEntry to SolrInputDocument
                                this.surrogates.put(this.configuration.toSolrInputDocument(doc));
                            }
                        } catch (MalformedURLException e) {
                        }
                    }
                } catch (Throwable ee) {
                    // bad line
                }
            }
        } else {
            this.saxParser.parse(this.inputSource, this);
        }
    } catch (final SAXParseException e) {
        ConcurrentLog.logException(e);
    } catch (final SAXException e) {
        ConcurrentLog.logException(e);
    } catch (final IOException e) {
        ConcurrentLog.logException(e);
    } finally {
        for (int i = 0; i < this.concurrency; i++) {
            try {
                this.surrogates.put(POISON_DOCUMENT);
            } catch (final InterruptedException e1) {
                ConcurrentLog.logException(e1);
            }
        }
        try {
            this.inputStream.close();
        } catch (final IOException e) {
            ConcurrentLog.logException(e);
        }
    }
}

From source file:org.vootoo.client.netty.util.ProtobufUtil.java

License:Apache License

public static void fillErrorMetadata(SolrProtocol.ExceptionBody.Builder protocolSolrException,
        NamedList<String> errorMetadata) {
    if (errorMetadata != null) {
        //errorMetadata one by one
        Iterator<Map.Entry<String, String>> it = errorMetadata.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> next = it.next();
            SolrProtocol.KeyValue.Builder metaBuilder = SolrProtocol.KeyValue.newBuilder();
            metaBuilder.setKey(next.getKey());
            metaBuilder.setValue(next.getValue());

            // errorMetadata one
            protocolSolrException.addMetadata(metaBuilder);
        }//w  w  w. j  a v a  2s  . c o m
    }
}

From source file:uk.co.flax.biosolr.FacetTreeGenerator.java

License:Apache License

/**
 * Convert a list of facets into a map, keyed by the facet term. 
 * @param facetValues the facet values./*  w  w  w . j  a v  a2s.  c  o m*/
 * @return a map of term - value for each entry.
 */
private Map<String, Integer> extractFacetValues(NamedList<Integer> facetValues) {
    Map<String, Integer> facetMap = new LinkedHashMap<>();
    for (Iterator<Entry<String, Integer>> it = facetValues.iterator(); it.hasNext();) {
        Entry<String, Integer> entry = it.next();
        if (entry.getValue() > 0) {
            facetMap.put(entry.getKey(), entry.getValue());
        }
    }

    return facetMap;
}