Search in sources :

Example 31 with ProviderException

use of org.apache.wiki.api.exceptions.ProviderException in project jspwiki by apache.

the class InsertPage method execute.

/**
 *  {@inheritDoc}
 */
@SuppressWarnings("unchecked")
public String execute(WikiContext context, Map<String, String> params) throws PluginException {
    WikiEngine engine = context.getEngine();
    StringBuilder res = new StringBuilder();
    String clazz = params.get(PARAM_CLASS);
    String includedPage = params.get(PARAM_PAGENAME);
    String style = params.get(PARAM_STYLE);
    String defaultstr = params.get(PARAM_DEFAULT);
    int section = TextUtil.parseIntParameter(params.get(PARAM_SECTION), -1);
    int maxlen = TextUtil.parseIntParameter(params.get(PARAM_MAXLENGTH), -1);
    if (style == null)
        style = DEFAULT_STYLE;
    if (maxlen == -1)
        maxlen = Integer.MAX_VALUE;
    if (includedPage != null) {
        WikiPage page = null;
        try {
            String pageName = engine.getFinalPageName(includedPage);
            if (pageName != null) {
                page = engine.getPage(pageName);
            } else {
                page = engine.getPage(includedPage);
            }
        } catch (ProviderException e) {
            res.append("<span class=\"error\">Page could not be found by the page provider.</span>");
            return res.toString();
        }
        if (page != null) {
            // 
            // Check for recursivity
            // 
            List<String> previousIncludes = (List<String>) context.getVariable(ATTR_RECURSE);
            if (previousIncludes != null) {
                if (previousIncludes.contains(page.getName())) {
                    return "<span class=\"error\">Error: Circular reference - you can't include a page in itself!</span>";
                }
            } else {
                previousIncludes = new ArrayList<String>();
            }
            previousIncludes.add(page.getName());
            context.setVariable(ATTR_RECURSE, previousIncludes);
            // 
            // Check for permissions
            // 
            AuthorizationManager mgr = engine.getAuthorizationManager();
            if (!mgr.checkPermission(context.getWikiSession(), PermissionFactory.getPagePermission(page, "view"))) {
                res.append("<span class=\"error\">You do not have permission to view this included page.</span>");
                return res.toString();
            }
            /**
             *  We want inclusion to occur within the context of
             *  its own page, because we need the links to be correct.
             */
            WikiContext includedContext = (WikiContext) context.clone();
            includedContext.setPage(page);
            String pageData = engine.getPureText(page);
            String moreLink = "";
            if (section != -1) {
                try {
                    pageData = TextUtil.getSection(pageData, section);
                } catch (IllegalArgumentException e) {
                    throw new PluginException(e.getMessage());
                }
            }
            if (pageData.length() > maxlen) {
                pageData = pageData.substring(0, maxlen) + " ...";
                moreLink = "<p><a href=\"" + context.getURL(WikiContext.VIEW, includedPage) + "\">More...</a></p>";
            }
            res.append("<div style=\"" + style + "\"" + (clazz != null ? " class=\"" + clazz + "\"" : "") + ">");
            res.append(engine.textToHTML(includedContext, pageData));
            res.append(moreLink);
            res.append("</div>");
            // 
            // Remove the name from the stack; we're now done with this.
            // 
            previousIncludes.remove(page.getName());
            context.setVariable(ATTR_RECURSE, previousIncludes);
        } else {
            if (defaultstr != null) {
                res.append(defaultstr);
            } else {
                res.append("There is no page called '" + includedPage + "'.  Would you like to ");
                res.append("<a href=\"" + context.getURL(WikiContext.EDIT, includedPage) + "\">create it?</a>");
            }
        }
    } else {
        res.append("<span class=\"error\">");
        res.append("You have to define a page!");
        res.append("</span>");
    }
    return res.toString();
}
Also used : WikiContext(org.apache.wiki.WikiContext) ProviderException(org.apache.wiki.api.exceptions.ProviderException) WikiPage(org.apache.wiki.WikiPage) PluginException(org.apache.wiki.api.exceptions.PluginException) List(java.util.List) ArrayList(java.util.ArrayList) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) WikiEngine(org.apache.wiki.WikiEngine)

Example 32 with ProviderException

use of org.apache.wiki.api.exceptions.ProviderException in project jspwiki by apache.

the class BasicSearchProvider method attachmentNames.

private String attachmentNames(WikiPage page, String separator) {
    if (m_engine.getAttachmentManager().hasAttachments(page)) {
        Collection attachments;
        try {
            attachments = m_engine.getAttachmentManager().listAttachments(page);
        } catch (ProviderException e) {
            log.error("Unable to get attachments for page", e);
            return "";
        }
        StringBuilder attachmentNames = new StringBuilder();
        for (Iterator it = attachments.iterator(); it.hasNext(); ) {
            Attachment att = (Attachment) it.next();
            attachmentNames.append(att.getName());
            if (it.hasNext())
                attachmentNames.append(separator);
        }
        return attachmentNames.toString();
    }
    return "";
}
Also used : ProviderException(org.apache.wiki.api.exceptions.ProviderException) Iterator(java.util.Iterator) Collection(java.util.Collection) Attachment(org.apache.wiki.attachment.Attachment)

Example 33 with ProviderException

use of org.apache.wiki.api.exceptions.ProviderException in project jspwiki by apache.

the class LuceneSearchProvider method findPages.

/**
 *  Searches pages using a particular combination of flags.
 *
 *  @param query The query to perform in Lucene query language
 *  @param flags A set of flags
 *  @return A Collection of SearchResult instances
 *  @throws ProviderException if there is a problem with the backend
 */
public Collection findPages(String query, int flags, WikiContext wikiContext) throws ProviderException {
    IndexSearcher searcher = null;
    ArrayList<SearchResult> list = null;
    Highlighter highlighter = null;
    try {
        String[] queryfields = { LUCENE_PAGE_CONTENTS, LUCENE_PAGE_NAME, LUCENE_AUTHOR, LUCENE_ATTACHMENTS };
        QueryParser qp = new MultiFieldQueryParser(Version.LUCENE_47, queryfields, getLuceneAnalyzer());
        // QueryParser qp = new QueryParser( LUCENE_PAGE_CONTENTS, getLuceneAnalyzer() );
        Query luceneQuery = qp.parse(query);
        if ((flags & FLAG_CONTEXTS) != 0) {
            highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"searchmatch\">", "</span>"), new SimpleHTMLEncoder(), new QueryScorer(luceneQuery));
        }
        try {
            File dir = new File(m_luceneDirectory);
            Directory luceneDir = new SimpleFSDirectory(dir, null);
            IndexReader reader = DirectoryReader.open(luceneDir);
            searcher = new IndexSearcher(reader);
        } catch (Exception ex) {
            log.info("Lucene not yet ready; indexing not started", ex);
            return null;
        }
        ScoreDoc[] hits = searcher.search(luceneQuery, MAX_SEARCH_HITS).scoreDocs;
        AuthorizationManager mgr = m_engine.getAuthorizationManager();
        list = new ArrayList<SearchResult>(hits.length);
        for (int curr = 0; curr < hits.length; curr++) {
            int docID = hits[curr].doc;
            Document doc = searcher.doc(docID);
            String pageName = doc.get(LUCENE_ID);
            WikiPage page = m_engine.getPage(pageName, WikiPageProvider.LATEST_VERSION);
            if (page != null) {
                if (page instanceof Attachment) {
                // Currently attachments don't look nice on the search-results page
                // When the search-results are cleaned up this can be enabled again.
                }
                PagePermission pp = new PagePermission(page, PagePermission.VIEW_ACTION);
                if (mgr.checkPermission(wikiContext.getWikiSession(), pp)) {
                    int score = (int) (hits[curr].score * 100);
                    // Get highlighted search contexts
                    String text = doc.get(LUCENE_PAGE_CONTENTS);
                    String[] fragments = new String[0];
                    if (text != null && highlighter != null) {
                        TokenStream tokenStream = getLuceneAnalyzer().tokenStream(LUCENE_PAGE_CONTENTS, new StringReader(text));
                        fragments = highlighter.getBestFragments(tokenStream, text, MAX_FRAGMENTS);
                    }
                    SearchResult result = new SearchResultImpl(page, score, fragments);
                    list.add(result);
                }
            } else {
                log.error("Lucene found a result page '" + pageName + "' that could not be loaded, removing from Lucene cache");
                pageRemoved(new WikiPage(m_engine, pageName));
            }
        }
    } catch (IOException e) {
        log.error("Failed during lucene search", e);
    } catch (ParseException e) {
        log.info("Broken query; cannot parse query ", e);
        throw new ProviderException("You have entered a query Lucene cannot process: " + e.getMessage());
    } catch (InvalidTokenOffsetsException e) {
        log.error("Tokens are incompatible with provided text ", e);
    } finally {
        if (searcher != null) {
            try {
                searcher.getIndexReader().close();
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
    return list;
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) TokenStream(org.apache.lucene.analysis.TokenStream) Query(org.apache.lucene.search.Query) TermQuery(org.apache.lucene.search.TermQuery) ProviderException(org.apache.wiki.api.exceptions.ProviderException) WikiPage(org.apache.wiki.WikiPage) Attachment(org.apache.wiki.attachment.Attachment) Document(org.apache.lucene.document.Document) ScoreDoc(org.apache.lucene.search.ScoreDoc) InvalidTokenOffsetsException(org.apache.lucene.search.highlight.InvalidTokenOffsetsException) StringReader(java.io.StringReader) Highlighter(org.apache.lucene.search.highlight.Highlighter) Directory(org.apache.lucene.store.Directory) SimpleFSDirectory(org.apache.lucene.store.SimpleFSDirectory) SimpleHTMLEncoder(org.apache.lucene.search.highlight.SimpleHTMLEncoder) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) QueryScorer(org.apache.lucene.search.highlight.QueryScorer) IOException(java.io.IOException) SimpleFSDirectory(org.apache.lucene.store.SimpleFSDirectory) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) NoRequiredPropertyException(org.apache.wiki.api.exceptions.NoRequiredPropertyException) InternalWikiException(org.apache.wiki.InternalWikiException) ParseException(org.apache.lucene.queryparser.classic.ParseException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) InvalidTokenOffsetsException(org.apache.lucene.search.highlight.InvalidTokenOffsetsException) IOException(java.io.IOException) ProviderException(org.apache.wiki.api.exceptions.ProviderException) MultiFieldQueryParser(org.apache.lucene.queryparser.classic.MultiFieldQueryParser) QueryParser(org.apache.lucene.queryparser.classic.QueryParser) IndexReader(org.apache.lucene.index.IndexReader) AuthorizationManager(org.apache.wiki.auth.AuthorizationManager) ParseException(org.apache.lucene.queryparser.classic.ParseException) SimpleHTMLFormatter(org.apache.lucene.search.highlight.SimpleHTMLFormatter) File(java.io.File) PagePermission(org.apache.wiki.auth.permissions.PagePermission)

Example 34 with ProviderException

use of org.apache.wiki.api.exceptions.ProviderException in project jspwiki by apache.

the class LuceneSearchProvider method getAttachmentContent.

/**
 * @param att Attachment to get content for. Filename extension is used to determine the type of the attachment.
 * @return String representing the content of the file.
 * FIXME This is a very simple implementation of some text-based attachment, mainly used for testing.
 * This should be replaced /moved to Attachment search providers or some other 'pluggable' wat to search attachments
 */
protected String getAttachmentContent(Attachment att) {
    AttachmentManager mgr = m_engine.getAttachmentManager();
    // FIXME: Add attachment plugin structure
    String filename = att.getFileName();
    boolean searchSuffix = false;
    for (String suffix : SEARCHABLE_FILE_SUFFIXES) {
        if (filename.endsWith(suffix)) {
            searchSuffix = true;
        }
    }
    String out = null;
    if (searchSuffix) {
        InputStream attStream = null;
        StringWriter sout = new StringWriter();
        try {
            attStream = mgr.getAttachmentStream(att);
            FileUtil.copyContents(new InputStreamReader(attStream), sout);
            out = sout.toString();
        } catch (ProviderException e) {
            log.error("Attachment cannot be loaded", e);
        } catch (IOException e) {
            log.error("Attachment cannot be loaded", e);
        } finally {
            IOUtils.closeQuietly(attStream);
            IOUtils.closeQuietly(sout);
        }
    }
    return out;
}
Also used : StringWriter(java.io.StringWriter) InputStreamReader(java.io.InputStreamReader) ProviderException(org.apache.wiki.api.exceptions.ProviderException) InputStream(java.io.InputStream) AttachmentManager(org.apache.wiki.attachment.AttachmentManager) IOException(java.io.IOException)

Example 35 with ProviderException

use of org.apache.wiki.api.exceptions.ProviderException in project jspwiki by apache.

the class LuceneSearchProvider method getLuceneAnalyzer.

private Analyzer getLuceneAnalyzer() throws ProviderException {
    try {
        Class<?> clazz = ClassUtil.findClass("", m_analyzerClass);
        Constructor<?> constructor = clazz.getConstructor(Version.LUCENE_47.getClass());
        Analyzer analyzer = (Analyzer) constructor.newInstance(Version.LUCENE_47);
        return analyzer;
    } catch (Exception e) {
        String msg = "Could not get LuceneAnalyzer class " + m_analyzerClass + ", reason: ";
        log.error(msg, e);
        throw new ProviderException(msg + e);
    }
}
Also used : ProviderException(org.apache.wiki.api.exceptions.ProviderException) Analyzer(org.apache.lucene.analysis.Analyzer) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) NoRequiredPropertyException(org.apache.wiki.api.exceptions.NoRequiredPropertyException) InternalWikiException(org.apache.wiki.InternalWikiException) ParseException(org.apache.lucene.queryparser.classic.ParseException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) InvalidTokenOffsetsException(org.apache.lucene.search.highlight.InvalidTokenOffsetsException) IOException(java.io.IOException) ProviderException(org.apache.wiki.api.exceptions.ProviderException)

Aggregations

ProviderException (org.apache.wiki.api.exceptions.ProviderException)42 WikiPage (org.apache.wiki.WikiPage)19 Attachment (org.apache.wiki.attachment.Attachment)16 IOException (java.io.IOException)13 WikiEngine (org.apache.wiki.WikiEngine)11 Collection (java.util.Collection)9 Iterator (java.util.Iterator)9 File (java.io.File)8 InputStream (java.io.InputStream)7 Date (java.util.Date)6 PagePermission (org.apache.wiki.auth.permissions.PagePermission)6 Permission (java.security.Permission)5 ArrayList (java.util.ArrayList)5 WikiContext (org.apache.wiki.WikiContext)5 PluginException (org.apache.wiki.api.exceptions.PluginException)5 AuthorizationManager (org.apache.wiki.auth.AuthorizationManager)5 AttachmentManager (org.apache.wiki.attachment.AttachmentManager)4 BufferedInputStream (java.io.BufferedInputStream)3 FileInputStream (java.io.FileInputStream)3 OutputStream (java.io.OutputStream)3