Example usage for org.apache.solr.response SolrQueryResponse setException

List of usage examples for org.apache.solr.response SolrQueryResponse setException

Introduction

In this page you can find the example usage for org.apache.solr.response SolrQueryResponse setException.

Prototype

public void setException(Exception e) 

Source Link

Document

Causes an error to be returned instead of the results.

Usage

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 a  2  s  .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.components.FilteredShowFileRequestHandler.java

License:Apache License

public static boolean isHiddenFile(SolrQueryRequest req, SolrQueryResponse rsp, String fnameIn,
        boolean reportError, Set<String> hiddenFiles) {
    String fname = fnameIn.toUpperCase(Locale.ROOT);
    if (hiddenFiles.contains(fname) || hiddenFiles.contains("*")) {
        if (reportError) {
            log.error("Cannot access " + fname);
            rsp.setException(
                    new SolrException(SolrException.ErrorCode.FORBIDDEN, "Can not access: " + fnameIn));
        }/*from w ww .j a  v a  2 s  .c  o  m*/
        return true;
    }

    // This is slightly off, a valid path is something like ./schema.xml. I don't think it's worth the effort though
    // to fix it to handle all possibilities though.
    if (fname.indexOf("..") >= 0 || fname.startsWith(".")) {
        if (reportError) {
            log.error("Invalid path: " + fname);
            rsp.setException(new SolrException(SolrException.ErrorCode.FORBIDDEN, "Invalid path: " + fnameIn));
        }
        return true;
    }

    // Make sure that if the schema is managed, we don't allow editing. Don't really want to put
    // this in the init since we're not entirely sure when the managed schema will get initialized relative to this
    // handler.
    SolrCore core = req.getCore();
    IndexSchema schema = core.getLatestSchema();
    if (schema instanceof ManagedIndexSchema) {
        String managed = schema.getResourceName();

        if (fname.equalsIgnoreCase(managed)) {
            return true;
        }
    }
    return false;
}

From source file:alba.components.FilteredShowFileRequestHandler.java

License:Apache License

public static String getAdminFileFromZooKeeper(SolrQueryRequest req, SolrQueryResponse rsp,
        SolrZkClient zkClient, Set<String> hiddenFiles) throws KeeperException, InterruptedException {
    String adminFile = null;//from  w  w w . java  2s.c om
    SolrCore core = req.getCore();

    final ZkSolrResourceLoader loader = (ZkSolrResourceLoader) core.getResourceLoader();
    String confPath = loader.getConfigSetZkPath();

    String fname = req.getParams().get("file", null);
    if (fname == null) {
        adminFile = confPath;
    } else {
        fname = fname.replace('\\', '/'); // normalize slashes
        if (isHiddenFile(req, rsp, fname, true, hiddenFiles)) {
            return null;
        }
        if (fname.startsWith("/")) { // Only files relative to conf are valid
            fname = fname.substring(1);
        }
        adminFile = confPath + "/" + fname;
    }

    // Make sure the file exists, is readable and is not a hidden file
    if (!zkClient.exists(adminFile, true)) {
        log.error("Can not find: " + adminFile);
        rsp.setException(new SolrException(SolrException.ErrorCode.NOT_FOUND, "Can not find: " + adminFile));
        return null;
    }

    return adminFile;
}

From source file:alba.components.FilteredShowFileRequestHandler.java

License:Apache License

public static File getAdminFileFromFileSystem(SolrQueryRequest req, SolrQueryResponse rsp,
        Set<String> hiddenFiles) {
    File adminFile = null;//from w w  w .  j  a  v a 2  s . c  om
    final SolrResourceLoader loader = req.getCore().getResourceLoader();
    File configdir = new File(loader.getConfigDir());
    if (!configdir.exists()) {
        // TODO: maybe we should just open it this way to start with?
        try {
            configdir = new File(loader.getClassLoader().getResource(loader.getConfigDir()).toURI());
        } catch (URISyntaxException e) {
            log.error("Can not access configuration directory!");
            rsp.setException(new SolrException(SolrException.ErrorCode.FORBIDDEN,
                    "Can not access configuration directory!", e));
            return null;
        }
    }
    String fname = req.getParams().get("file", null);
    if (fname == null) {
        adminFile = configdir;
    } else {
        fname = fname.replace('\\', '/'); // normalize slashes
        if (hiddenFiles.contains(fname.toUpperCase(Locale.ROOT))) {
            log.error("Can not access: " + fname);
            rsp.setException(new SolrException(SolrException.ErrorCode.FORBIDDEN, "Can not access: " + fname));
            return null;
        }
        if (fname.indexOf("..") >= 0) {
            log.error("Invalid path: " + fname);
            rsp.setException(new SolrException(SolrException.ErrorCode.FORBIDDEN, "Invalid path: " + fname));
            return null;
        }
        adminFile = new File(configdir, fname);
    }
    return adminFile;
}

From source file:jp.aegif.nemaki.NemakiCoreAdminHandler.java

License:Open Source License

private void changePassword(SolrQueryResponse rsp, CoreTracker tracker, String repositoryId,
        SolrParams params) {/*from   w  ww . jav  a2s  . c o  m*/
    //Validation
    if (StringUtils.isEmpty(repositoryId)) {
        rsp.setException(new Exception("repositoryId is not set."));
        return;
    }

    String password = params.get("password");
    if (StringUtils.isEmpty(password)) {
        rsp.setException(new Exception("New password is not set."));
        return;
    }

    String currentPassword = params.get("currentPassword");
    if (StringUtils.isEmpty(password)) {
        rsp.setException(new Exception("Current password is not set."));
        return;
    }

    //Execute
    RepositorySettings settings = CmisSessionFactory.getRepositorySettings();
    RepositorySetting setting = settings.get(repositoryId);
    if (setting == null) {
        rsp.setException(new Exception("Specified repository does not exist."));
        return;
    }
    if (!currentPassword.equals(setting.getPassword())) {
        rsp.setException(new Exception("Current password does not match."));
        return;
    }
    setting.setPassword(password);
    CmisSessionFactory.modifyRepositorySettings(settings);

    rsp.add("Result", "Successfully password changed!");

}

From source file:org.codeexample.jeffery.solr.ThreadedUpdateRequestHandler.java

License:Apache License

private ExecutorService importStreamsMultiThreaded(final SolrQueryRequest req, final SolrQueryResponse rsp,
        List<ContentStream> streams) throws InterruptedException, IOException {
    ExecutorService executor = null;
    SolrParams params = req.getParams();

    final UpdateRequestProcessorChain processorChain = req.getCore()
            .getUpdateProcessingChain(params.get(UpdateParams.UPDATE_CHAIN));

    UpdateRequestProcessor processor = processorChain.createProcessor(req, rsp);
    try {//from   www .  j ava  2 s.  co m
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();

        resultMap.put("start_time", new Date());
        List<Map<String, Object>> details = new ArrayList<Map<String, Object>>();

        try {

            int threads = determineThreadsNumber(params, streams.size());
            ThreadFactory threadFactory = new ThreadFactory() {
                public Thread newThread(Runnable r) {
                    return new Thread(r, "threadedReqeustHandler-" + new Date());
                }
            };
            executor = Executors.newFixedThreadPool(threads, threadFactory);
            String contentType = params.get(CommonParams.STREAM_CONTENTTYPE);

            Iterator<ContentStream> iterator = streams.iterator();
            while (iterator.hasNext()) {
                ContentStream stream = iterator.next();
                iterator.remove();
                if (stream instanceof ContentStreamBase) {
                    ((ContentStreamBase) stream).setContentType(contentType);

                }
                submitTask(req, rsp, processorChain, executor, stream, details);
            }

            executor.shutdown();

            boolean terminated = executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
            if (!terminated) {
                throw new RuntimeException("Request takes too much time");
            }
            // Perhaps commit from the parameters
            RequestHandlerUtils.handleCommit(req, processor, params, false);
            RequestHandlerUtils.handleRollback(req, processor, params, false);
        } finally {
            resultMap.put("end_time", new Date());

            // check whether there is error in details
            for (Map<String, Object> map : details) {
                Exception ex = (Exception) map.get("exception");
                if (ex != null) {
                    rsp.setException(ex);
                    if (ex instanceof SolrException) {
                        rsp.add("status", ((SolrException) ex).code());
                    } else {
                        rsp.add("status", SolrException.ErrorCode.BAD_REQUEST);
                    }
                    break;
                }
            }
        }
        resultMap.put("details", details);
        rsp.add("result", resultMap);
        return executor;
    } finally {
        if (executor != null && !executor.isShutdown()) {
            executor.shutdownNow();
        }
        // finish the request
        processor.finish();
    }
}

From source file:org.codeexample.jeffery.solr.ThreadedUpdateRequestHandler.java

License:Apache License

private void submitTask(final SolrQueryRequest req, final SolrQueryResponse rsp,
        final UpdateRequestProcessorChain processorChain, ExecutorService executor, final ContentStream stream,
        final List<Map<String, Object>> rspResult) {
    Thread thread = new Thread() {
        public void run() {
            Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("start_time", new Date().toString());

            if (stream instanceof ContentStreamBase.FileStream) {
                map.put("Import File: ", ((ContentStreamBase.FileStream) stream).getName());
            }/*  w w  w .j  a va2  s .  c o m*/
            try {
                UpdateRequestProcessor processor = null;
                try {
                    processor = processorChain.createProcessor(req, rsp);

                    ContentStreamLoader documentLoader = newLoader(req, processor);

                    documentLoader.load(req, rsp, stream, processor);
                    System.err.println(rsp);

                } finally {
                    if (processor != null) {
                        // finish the request
                        processor.finish();
                    }
                }
            } catch (Exception e) {
                rsp.setException(e);
            } finally {
                map.put("end_time", new Date().toString());
                if (rsp.getException() != null) {
                    map.put("exception", rsp.getException());
                }
                rspResult.add(map);
            }

        };
    };

    executor.execute(thread);
}