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

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

Introduction

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

Prototype

public void add(String name, T val) 

Source Link

Document

Adds a name/value pair to the end of the list.

Usage

From source file:alba.components.FilteredShowFileRequestHandler.java

License:Apache License

private void showFromZooKeeper(SolrQueryRequest req, SolrQueryResponse rsp, CoreContainer coreContainer)
        throws KeeperException, InterruptedException, UnsupportedEncodingException {

    SolrZkClient zkClient = coreContainer.getZkController().getZkClient();

    String adminFile = getAdminFileFromZooKeeper(req, rsp, zkClient, hiddenFiles);

    if (adminFile == null) {
        return;/*from   w  ww .j av a 2 s.  co m*/
    }

    // Show a directory listing
    List<String> children = zkClient.getChildren(adminFile, null, true);
    if (children.size() > 0) {

        NamedList<SimpleOrderedMap<Object>> files = new SimpleOrderedMap<>();
        for (String f : children) {
            if (isHiddenFile(req, rsp, f, false, hiddenFiles)) {
                continue;
            }

            SimpleOrderedMap<Object> fileInfo = new SimpleOrderedMap<>();
            files.add(f, fileInfo);
            List<String> fchildren = zkClient.getChildren(adminFile + "/" + f, null, true);
            if (fchildren.size() > 0) {
                fileInfo.add("directory", true);
            } else {
                // TODO? content type
                fileInfo.add("size", f.length());
            }
            // TODO: ?
            // fileInfo.add( "modified", new Date( f.lastModified() ) );
        }
        rsp.add("files", files);
    } else {
        // Include the file contents
        // The file logic depends on RawResponseWriter, so force its use.
        ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
        params.set(CommonParams.WT, "raw");
        req.setParams(params);

        ContentStreamBase content = new ContentStreamBase.ByteArrayStream(
                zkClient.getData(adminFile, null, null, true), adminFile);
        content.setContentType(req.getParams().get(USE_CONTENT_TYPE));

        // Velocity parsing here!

        // http://velocity.apache.org/engine/devel/developer-guide.html#The_Context
        Velocity.init();

        VelocityContext context = new VelocityContext();

        //add some vars??
        //context.put( "context", new String("Velocity") );

        for (int i = 0; i < rsp.getValues().size(); i++) {
            context.put(rsp.getValues().getName(i), rsp.getValues().getVal(i));
        }

        Template template = null;

        String fname = req.getParams().get("file", null);

        try {
            //TODO what if fname is null?
            template = Velocity.getTemplate(fname);
        } catch (ResourceNotFoundException rnfe) {
            // couldn't find the template, try to load it

            // TODO it should be fired only for SOME mimetypes (..through an annotation??)
            StringBuilder sb = this.getTemplate(content);

            RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
            StringReader reader = new StringReader(sb.toString());
            SimpleNode node = null;
            try {
                node = runtimeServices.parse(reader, fname);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                logger.error("error while parsing new template", e);
            }

            template = new Template();

            template.setRuntimeServices(runtimeServices);

            if (node != null) {
                template.setData(node);
            } else {
                logger.error("node null, can't set on template");
            }

            template.initDocument();

        } catch (ParseErrorException pee) {
            // syntax error: problem parsing the template
            logger.error("error while parsing template: ", pee);

        } catch (MethodInvocationException mie) {
            // something invoked in the template
            // threw an exception
            logger.error("error while parsing temaplate: ", mie);
        } catch (Exception e) {
            logger.error("error while parsing temaplate: ", e);
        }

        StringWriter sw = new StringWriter();

        template.merge(context, sw);

        // http://stackoverflow.com/questions/18571223/how-to-convert-java-string-into-byte
        content = new ContentStreamBase.ByteArrayStream(
                sw.getBuffer().toString().getBytes(Charset.forName("UTF-8")), adminFile);
        content.setContentType(req.getParams().get(USE_CONTENT_TYPE));

        rsp.add(RawResponseWriter.CONTENT, content);
    }
    rsp.setHttpCaching(false);
}

From source file:alba.components.FilteredShowFileRequestHandler.java

License:Apache License

private void showFromFileSystem(SolrQueryRequest req, SolrQueryResponse rsp) {
    File adminFile = getAdminFileFromFileSystem(req, rsp, hiddenFiles);

    if (adminFile == null) { // exception already recorded
        return;/*from ww w .j  a v  a2  s  .c om*/
    }

    // Make sure the file exists, is readable and is not a hidden file
    if (!adminFile.exists()) {
        log.error("Can not find: " + adminFile.getName() + " [" + adminFile.getAbsolutePath() + "]");
        rsp.setException(new SolrException(ErrorCode.NOT_FOUND,
                "Can not find: " + adminFile.getName() + " [" + adminFile.getAbsolutePath() + "]"));
        return;
    }
    if (!adminFile.canRead() || adminFile.isHidden()) {
        log.error("Can not show: " + adminFile.getName() + " [" + adminFile.getAbsolutePath() + "]");
        rsp.setException(new SolrException(ErrorCode.NOT_FOUND,
                "Can not show: " + adminFile.getName() + " [" + adminFile.getAbsolutePath() + "]"));
        return;
    }

    // Show a directory listing
    if (adminFile.isDirectory()) {
        // it's really a directory, just go for it.
        int basePath = adminFile.getAbsolutePath().length() + 1;
        NamedList<SimpleOrderedMap<Object>> files = new SimpleOrderedMap<>();
        for (File f : adminFile.listFiles()) {
            String path = f.getAbsolutePath().substring(basePath);
            path = path.replace('\\', '/'); // normalize slashes

            if (isHiddenFile(req, rsp, f.getName().replace('\\', '/'), false, hiddenFiles)) {
                continue;
            }

            SimpleOrderedMap<Object> fileInfo = new SimpleOrderedMap<>();
            files.add(path, fileInfo);
            if (f.isDirectory()) {
                fileInfo.add("directory", true);
            } else {
                // TODO? content type
                fileInfo.add("size", f.length());
            }
            fileInfo.add("modified", new Date(f.lastModified()));
        }
        rsp.add("files", files);
    } else {
        // Include the file contents
        //The file logic depends on RawResponseWriter, so force its use.
        ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
        params.set(CommonParams.WT, "raw");
        req.setParams(params);

        ContentStreamBase content = new ContentStreamBase.FileStream(adminFile);
        content.setContentType(req.getParams().get(USE_CONTENT_TYPE));

        rsp.add(RawResponseWriter.CONTENT, content);
    }
    rsp.setHttpCaching(false);
}

From source file:alba.solr.core.Loader.java

License:Apache License

@Override
public NamedList<String> getStatistics() {
    NamedList<String> nl = new NamedList<String>();
    nl.add("prova", "abc");
    return nl;/*from   w  w w  . j a v  a  2 s  . c o m*/
}

From source file:at.newmedialab.lmf.util.solr.suggestion.service.SuggestionService.java

License:Apache License

public SuggestionService(SolrCore solrCore, NamedList args) {

    NamedList l = new NamedList();

    //set spellcheck component if there is one
    if (((ArrayList) args.get("first-components")).contains("spellcheck")) {
        List component = new ArrayList<String>();
        component.add("spellcheck");
        l.add("first-components", component);
        spellcheck_enabled = true;/*  ww w.  ja v  a  2  s .c  om*/
    }

    this.solrCore = solrCore;
    this.searchHandler = new SearchHandler();
    this.searchHandler.init(l);
    this.searchHandler.inform(solrCore);
}

From source file:cn.howardliu.lucene.extension.ManagedSynonymFilterFactory.java

License:Apache License

/**
 * Called once, during core initialization, to initialize any analysis components
 * that depend on the data managed by this resource. It is important that the
 * analysis component is only initialized once during core initialization so that
 * text analysis is consistent, especially in a distributed environment, as we
 * don't want one server applying a different set of stop words than other servers.
 *//*from   ww w  .  j  a va2  s.com*/
@SuppressWarnings("unchecked")
@Override
public void onManagedResourceInitialized(NamedList<?> initArgs, final ManagedResource res)
        throws SolrException {
    NamedList<Object> args = (NamedList<Object>) initArgs;
    args.add("synonyms", getResourceId());
    args.add("expand", "false");
    args.add("format", "solr");

    Map<String, String> filtArgs = new HashMap<>();
    for (Map.Entry<String, ?> entry : args) {
        filtArgs.put(entry.getKey(), entry.getValue().toString());
    }
    // create the actual filter factory that pulls the synonym mappings
    // from synonymMappings using a custom parser implementation
    delegate = new SynonymFilterFactory(filtArgs) {
        @Override
        protected SynonymMap loadSynonyms(ResourceLoader loader, String cname, boolean dedup, Analyzer analyzer)
                throws IOException, ParseException {
            CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
                    .onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
            ManagedSynonymParser parser = new ManagedSynonymParser((SynonymManager) res, dedup, analyzer);
            // ???
            InputStreamReader in = null;
            if (StringUtils.isNotBlank(synonymFile)) {
                in = new InputStreamReader(loader.openResource(synonymFile), decoder);
            }
            parser.parse(in);
            return parser.build();
        }
    };
    try {
        delegate.inform(res.getResourceLoader());
    } catch (IOException e) {
        throw new SolrException(ErrorCode.SERVER_ERROR, e);
    }
}

From source file:com.doculibre.constellio.services.AutocompleteServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
static private NamedList<Object> suggest(String q, String fieldName, SolrServer server, Boolean isStringField) {
    NamedList<Object> returnList = new NamedList<Object>();

    // escape special characters
    SolrQuery query = new SolrQuery();

    /*//from w  ww  .j  av  a2s . co  m
     * // * Set terms.lower to the input term
     * query.setParam(TermsParams.TERMS_LOWER, q); // * Set terms.prefix to
     * the input term query.setParam(TermsParams.TERMS_PREFIX, q); // * Set
     * terms.lower.incl to false
     * query.setParam(TermsParams.TERMS_LOWER_INCLUSIVE, "false"); // * Set
     * terms.fl to the name of the source field
     * query.setParam(TermsParams.TERMS_FIELD, fieldName);
     */

    query.setParam(TermsParams.TERMS_FIELD, fieldName);// query.addTermsField("spell");
    query.setParam(TermsParams.TERMS_LIMIT, TERMS_LIMIT);// query.setTermsLimit(MAX_TERMS);
    query.setParam(TermsParams.TERMS, "true");// query.setTerms(true);
    query.setParam(TermsParams.TERMS_LOWER, q);// query.setTermsLower(q);
    query.setParam(TermsParams.TERMS_PREFIX, q);// query.setTermsPrefix(q);
    query.setParam(TermsParams.TERMS_MINCOUNT, TERMS_MINCOUNT);

    query.setRequestHandler(SolrServices.AUTOCOMPLETE_QUERY_NAME);

    try {
        QueryResponse qr = server.query(query);
        NamedList<Object> values = qr.getResponse();
        NamedList<Object> terms = (NamedList<Object>) values.get("terms");// TermsResponse
        // resp
        // =
        // qr.getTermsResponse();
        NamedList<Object> suggestions = (NamedList<Object>) terms.get(fieldName);// items
        // =
        // resp.getTerms("spell");
        if (!isStringField) {
            q = AnalyzerUtils.analyzePhrase(q, false);
        }

        for (int i = 0; i < suggestions.size(); i++) {
            String currentSuggestion = suggestions.getName(i);
            // System.out.println(currentSuggestion);
            if (isStringField) {
                if (currentSuggestion.contains(q)) {
                    // String suffix =
                    // StringUtils.substringAfter(currentSuggestion, q);
                    // if (suffix.isEmpty() &&
                    // !currentSuggestion.equals(q)){
                    // //q n est pas dans currentSuggestion
                    // break;
                    // }
                    if (currentSuggestion.contains(SPECIAL_CHAR)) {
                        // le resultat de recherche retourne des fois une
                        // partie de la valeur existant
                        // dans le champ!
                        currentSuggestion = StringUtils.substringAfter(currentSuggestion, SPECIAL_CHAR);
                    }
                    returnList.add(currentSuggestion, suggestions.getVal(i));
                }
            } else {
                currentSuggestion = AnalyzerUtils.analyzePhrase(currentSuggestion, false);
                if (currentSuggestion.contains(q)) {
                    returnList.add(currentSuggestion, suggestions.getVal(i));
                }
            }
        }

    } catch (SolrServerException e) {
        throw new RuntimeException(e);
    }
    return returnList;
}

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

License:Open Source License

public static NamedList<Object> getErrorNamedList(Exception e, SolrParams solrParams) {
    NamedList<Object> responseHeader = new NamedList<Object>();
    responseHeader.add(ServletsConstants.RESPONSE_STATUS, 500);

    NamedList<Object> error = new NamedList<Object>();
    error.add(ServletsConstants.MESSAGE, e.getMessage());
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);/*from w  w  w.  j  a v a2 s.co  m*/
    pw.flush();
    pw.close();
    error.add(ServletsConstants.STACK_TRACE, sw.getBuffer().toString());

    addParams(responseHeader, solrParams);

    NamedList<Object> nl = new NamedList<Object>();
    nl.add(ServletsConstants.RESPONSE_HEADER, responseHeader);
    nl.add(ServletsConstants.ERROR, error);
    return nl;
}

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

License:Open Source License

public static NamedList<Object> getSuccessfulNamedList(SolrParams solrParams) {
    NamedList<Object> responseHeader = new NamedList<Object>();
    responseHeader.add(ServletsConstants.RESPONSE_STATUS, 0);
    NamedList<Object> nl = new NamedList<Object>();
    nl.add(ServletsConstants.RESPONSE_HEADER, responseHeader);
    addParams(responseHeader, solrParams);
    return nl;/*from   www. ja  v a2 s  .c  o m*/
}

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

License:Open Source License

private static void addParams(NamedList<Object> responseHeader, SolrParams solrParams) {
    NamedList<Object> params = new NamedList<Object>();
    responseHeader.add("params", params);
    Iterator<String> enumParams = solrParams.getParameterNamesIterator();
    while (enumParams.hasNext()) {
        String param = enumParams.next();
        if (!param.equals(ServletsConstants.DIGEST_PARAM)) {
            String[] values = solrParams.getParams(param);
            params.add(param, values.length > 1 ? Arrays.asList(values) : values[0]);
        }//  ww w. j  a  v  a 2  s  . c  om
    }
}

From source file:com.doculibre.constellio.spellchecker.SpellChecker.java

License:Open Source License

private void addNamedList(NamedList<Object> mainList, String word, boolean missSpelled,
        List<String> suggestions) {
    NamedList<Object> nlWord = new NamedList<Object>();
    nlWord.add("frequency", missSpelled ? 0 : 1);
    NamedList<Object> suggestionsNamedList = new NamedList<Object>();
    if (suggestions != null) {
        for (String suggestedWord : suggestions) {
            NamedList<Object> nlSuggestedWord = new NamedList<Object>();
            nlSuggestedWord.add("frequency", 1);
            suggestionsNamedList.add(suggestedWord, nlSuggestedWord);
        }//ww w .ja  va2 s  .  co m
    }
    nlWord.add("suggestions", suggestionsNamedList);
    mainList.add(word, nlWord);
}