Example usage for org.apache.solr.request SolrQueryRequest setParams

List of usage examples for org.apache.solr.request SolrQueryRequest setParams

Introduction

In this page you can find the example usage for org.apache.solr.request SolrQueryRequest setParams.

Prototype

void setParams(SolrParams params);

Source Link

Document

Change the parameters for this request.

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;/* w w w .  ja  v  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;//w w w.  ja v a2s  . c o  m
    }

    // 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.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 w w .  j  a  v a2s  .co  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:com.adr.bigdata.search.product.fe.BaseSuggestionHandler.java

@Override
public void handleRequest(SolrQueryRequest req, SolrQueryResponse rsp) {
    String cacheKey = SolrParamUtils.transform(req.getParams());
    try {/*from  w w  w  . j  a v a 2  s .c  om*/
        String cacheResponse = this.rdModel.get(cacheKey);
        if (cacheResponse == null) {
            //cacheMiss
            try {
                final Object[] terms = new Object[1];
                suggestionLogic.execute(req, rsp, new Callable() {
                    @Override
                    public void call(Object... args) {
                        terms[0] = args[0];
                    }
                });
                SolrQueryResponse _rsp = new SolrQueryResponse();
                super.handleRequest(req, _rsp);
                suggestionLogic.writeRsp(req, _rsp, terms[0]);
                String result = outerString(req, _rsp);
                if (!zeroResult(_rsp)) {
                    this.rdModel.put(cacheKey, result);
                }
                ModifiableSolrParams params = new ModifiableSolrParams(req.getParams());
                params.set("vincache", true);
                SolrParams _params = SolrParams.wrapDefaults(params, defaults);
                _params = SolrParams.wrapAppended(_params, appends);
                req.setParams(_params);
                rsp.add("vincache", result);
            } catch (Exception e) {
                error(req, rsp);
                getLogger().error("", e);
            }

        } else {
            //cache hit
            ModifiableSolrParams solrParam = new ModifiableSolrParams(req.getParams());
            solrParam.set("vincache", true);
            SolrParams params = SolrParams.wrapAppended(solrParam, appends);
            params = SolrParams.wrapDefaults(params, defaults);
            req.setParams(params);
            rsp.add("vincache", cacheResponse);
        }

    } catch (Exception cacheEx) {
        getLogger().error("fail to get from redis cache.....{}", cacheEx.getMessage());
        try {
            final Object[] terms = new Object[1];

            suggestionLogic.execute(req, rsp, new Callable() {
                @Override
                public void call(Object... args) {
                    terms[0] = args[0];
                }
            });
            super.handleRequest(req, rsp);
            suggestionLogic.writeRsp(req, rsp, terms[0]);
        } catch (Exception e) {
            error(req, rsp);
            getLogger().error("", e);
        }
    }
}

From source file:com.doculibre.constellio.solr.handler.component.ManifoldCFAuthorizationComponent.java

License:Open Source License

@Override
public void prepare(ResponseBuilder rb) throws IOException {
    SolrQueryRequest req = rb.req;
    SolrParams params = req.getParams();

    // A runtime param can skip
    if (!params.getBool(ENABLE, true)) {
        return;/*from   w w w  .  j  ava  2  s . c  o m*/
    }

    boolean hasManifoldConnector = false;

    String collectioName = params.get(ConstellioSolrQueryParams.COLLECTION_NAME);
    RecordCollectionServices recordCollectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection recordCollection = recordCollectionServices.get(collectioName);
    if (recordCollection != null) {
        for (ConnectorInstance connector : recordCollection.getConnectorInstances()) {
            if (connector.getConnectorType().getName().equals(ManifoldCFConnectorType.CONNECTOR_TYPE_NAME)) {
                hasManifoldConnector = true;
                break;
            } else if (connector.getConnectorType().getName()
                    .equals(IntelliGIDConnectorType.CONNECTOR_TYPE_NAME)) {
                hasManifoldConnector = true;
                break;
            }
        }
    }

    //skip calling the component if we don't use the service (the manifoldcf server could not be up)
    if (hasManifoldConnector) {
        ConstellioUser user;
        String userIdStr = params.get(ConstellioSolrQueryParams.USER_ID);
        if (userIdStr != null) {
            UserServices userServices = ConstellioSpringUtils.getUserServices();
            try {
                user = userServices.get(new Long(userIdStr));
            } catch (NumberFormatException e) {
                user = null;
            }
        } else {
            user = null;
        }

        if (user != null) {
            ModifiableSolrParams newParams = new ModifiableSolrParams(params);
            newParams.add(AUTHENTICATED_USER_NAME, user.getUsername() + "@" + user.getDomain());
            req.setParams(newParams);
        } else {
            ModifiableSolrParams newParams = new ModifiableSolrParams(params);
            newParams.add(AUTHENTICATED_USER_NAME, "guest@guest");
            req.setParams(newParams);
        }
        super.prepare(rb);
    }
}

From source file:com.kmwllc.search.graph.GraphQueryOldTest.java

License:Open Source License

private SolrQueryRequest createRequest(String query) {
    SolrQueryRequest qr = req(query);
    NamedList<Object> par = qr.getParams().toNamedList();
    par.add("defType", "kmw");
    par.add("debug", "true");
    par.add("rows", "10");
    par.add("fl", "id,node_id,edge_id");
    par.remove("qt");
    par.add("qt", "/select");
    // par.add("")
    SolrParams newp = SolrParams.toSolrParams(par);
    qr.setParams(newp);
    return qr;//from   w  w  w .j  a va 2 s  .c  om
}

From source file:com.kmwllc.search.graph.GraphQueryOldTest.java

License:Open Source License

private SolrQueryRequest createRequestWithTFilter(String query, String traversalFilter) {
    SolrQueryRequest qr = req(query);
    NamedList par = qr.getParams().toNamedList();
    par.add("traversalFilter", traversalFilter);
    par.add("defType", "graph");

    par.add("debug", "true");
    par.add("rows", "10");
    par.add("fl", "id,node_id,edge_id");
    par.remove("qt");
    par.add("qt", "/select");
    // par.add("")
    SolrParams newp = SolrParams.toSolrParams(par);
    qr.setParams(newp);
    return qr;/*from   ww  w . j a  v a2s.  c  om*/
}

From source file:com.kmwllc.search.graph.GraphQueryTest.java

License:Open Source License

private SolrQueryRequest createRequest(String query) {
    SolrQueryRequest qr = req(query);
    NamedList<Object> par = qr.getParams().toNamedList();
    par.add("defType", "graph");
    par.add("debug", "true");
    par.add("rows", "10");
    par.add("fl", "id,node_id,edge_id");
    par.remove("qt");
    par.add("qt", "/select");
    // par.add("")
    SolrParams newp = SolrParams.toSolrParams(par);
    qr.setParams(newp);
    return qr;/*from  w w  w . j  a va 2  s. c  o  m*/
}

From source file:com.kmwllc.search.graph.LargeGraphQueryTest.java

License:Open Source License

private SolrQueryRequest createRequestWithTFilter(String query, String traversalFilter) {
    SolrQueryRequest qr = req(query);
    NamedList<Object> par = qr.getParams().toNamedList();
    par.add("traversalFilter", traversalFilter);
    par.add("defType", "kmw");

    par.add("debug", "true");
    par.add("rows", "10");
    par.add("fl", "id,node_id,edge_id");
    par.remove("qt");
    par.add("qt", "/select");
    // par.add("")
    SolrParams newp = SolrParams.toSolrParams(par);
    qr.setParams(newp);
    return qr;//from  w  w  w.j  ava2 s.  co m
}

From source file:com.tsgrp.solr.handler.NYPhilGetTagsHandler.java

License:Mozilla Public License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse res)
        throws Exception, ParseException, InstantiationException, IllegalAccessException {
    NamedList<Object> params = req.getParams().toNamedList();

    String assetId = (String) params.get(PARAM_ASSET_ID);
    if (assetId == null || assetId.trim().length() < 0) {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Asset Id required to retrieve tags.");
    }//from   w  w w. ja  v  a2  s.  c o m

    boolean allTags = (params.get(PARAM_ALL_TAGS) != null
            && Boolean.parseBoolean((String) params.get(PARAM_ALL_TAGS)));

    StringBuffer q = new StringBuffer("+").append(NYPhilSolrConstants.NPT_ASSET_ID_ESC).append(":")
            .append(QueryParser.escape(assetId));

    if (!allTags) {
        q.append(" +").append(NYPhilSolrConstants.NPT_STATUS_ESC).append(":")
                .append(NYPhilSolrConstants.STATUS_APPROVED);
    }

    String cb = (String) params.get(PARAM_CALLBACK);
    if (cb != null && cb.length() > 0) {
        params.add("json.wrf", cb);
    }

    params.add(CommonParams.HEADER_ECHO_PARAMS, "explicit");
    params.add(CommonParams.WT, "json");
    params.add("json.nl", "map");

    params.add(CommonParams.Q, q.toString());
    params.add(CommonParams.ROWS, 1000);

    req.setParams(SolrParams.toSolrParams(params));

    super.handleRequestBody(req, res);
}