Search in sources :

Example 56 with Attachment

use of org.apache.wiki.attachment.Attachment 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 57 with Attachment

use of org.apache.wiki.attachment.Attachment 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 58 with Attachment

use of org.apache.wiki.attachment.Attachment in project jspwiki by apache.

the class AttachmentsIteratorTag method doStartTag.

/**
 *  {@inheritDoc}
 */
@Override
public final int doStartTag() {
    m_wikiContext = (WikiContext) pageContext.getAttribute(WikiTagBase.ATTR_CONTEXT, PageContext.REQUEST_SCOPE);
    WikiEngine engine = m_wikiContext.getEngine();
    AttachmentManager mgr = engine.getAttachmentManager();
    WikiPage page;
    page = m_wikiContext.getPage();
    if (!mgr.attachmentsEnabled()) {
        return SKIP_BODY;
    }
    try {
        if (page != null && engine.pageExists(page)) {
            Collection atts = mgr.listAttachments(page);
            if (atts == null) {
                log.debug("No attachments to display.");
                // There are no attachments included
                return SKIP_BODY;
            }
            m_iterator = atts.iterator();
            if (m_iterator.hasNext()) {
                Attachment att = (Attachment) m_iterator.next();
                WikiContext context = (WikiContext) m_wikiContext.clone();
                context.setPage(att);
                pageContext.setAttribute(WikiTagBase.ATTR_CONTEXT, context, PageContext.REQUEST_SCOPE);
                pageContext.setAttribute(getId(), att);
            } else {
                return SKIP_BODY;
            }
        } else {
            return SKIP_BODY;
        }
        return EVAL_BODY_BUFFERED;
    } catch (ProviderException e) {
        log.fatal("Provider failed while trying to iterator through history", e);
    // FIXME: THrow something.
    }
    return SKIP_BODY;
}
Also used : WikiContext(org.apache.wiki.WikiContext) ProviderException(org.apache.wiki.api.exceptions.ProviderException) WikiPage(org.apache.wiki.WikiPage) Collection(java.util.Collection) Attachment(org.apache.wiki.attachment.Attachment) AttachmentManager(org.apache.wiki.attachment.AttachmentManager) WikiEngine(org.apache.wiki.WikiEngine)

Example 59 with Attachment

use of org.apache.wiki.attachment.Attachment in project jspwiki by apache.

the class LinkTag method figureOutURL.

/**
 *  This method figures out what kind of an URL should be output.  It mirrors heavily
 *  on JSPWikiMarkupParser.handleHyperlinks();
 *
 * @return the URL
 * @throws ProviderException
 */
private String figureOutURL() throws ProviderException {
    String url = null;
    WikiEngine engine = m_wikiContext.getEngine();
    if (m_pageName == null) {
        WikiPage page = m_wikiContext.getPage();
        if (page != null) {
            m_pageName = page.getName();
        }
    }
    if (m_templatefile != null) {
        String params = addParamsForRecipient(null, m_containedParams);
        String template = engine.getTemplateDir();
        url = engine.getURL(WikiContext.NONE, "templates/" + template + "/" + m_templatefile, params, false);
    } else if (m_jsp != null) {
        String params = addParamsForRecipient(null, m_containedParams);
        // url = m_wikiContext.getURL( WikiContext.NONE, m_jsp, params );
        url = engine.getURL(WikiContext.NONE, m_jsp, params, m_absolute);
    } else if (m_ref != null) {
        int interwikipoint;
        if (new LinkParsingOperations(m_wikiContext).isExternalLink(m_ref)) {
            url = m_ref;
        } else if ((interwikipoint = m_ref.indexOf(":")) != -1) {
            String extWiki = m_ref.substring(0, interwikipoint);
            String wikiPage = m_ref.substring(interwikipoint + 1);
            url = engine.getInterWikiURL(extWiki);
            if (url != null) {
                url = TextUtil.replaceString(url, "%s", wikiPage);
            }
        } else if (m_ref.startsWith("#")) {
        // Local link
        } else if (TextUtil.isNumber(m_ref)) {
        // Reference
        } else {
            int hashMark = -1;
            String parms = (m_version != null) ? "version=" + getVersion() : null;
            // 
            // Internal wiki link, but is it an attachment link?
            // 
            WikiPage p = engine.getPage(m_pageName);
            if (p instanceof Attachment) {
                url = m_wikiContext.getURL(WikiContext.ATTACH, m_pageName);
            } else if ((hashMark = m_ref.indexOf('#')) != -1) {
                // It's an internal Wiki link, but to a named section
                String namedSection = m_ref.substring(hashMark + 1);
                String reallink = m_ref.substring(0, hashMark);
                reallink = MarkupParser.cleanLink(reallink);
                String matchedLink;
                String sectref = "";
                if ((matchedLink = engine.getFinalPageName(reallink)) != null) {
                    sectref = "section-" + engine.encodeName(matchedLink) + "-" + namedSection;
                    sectref = "#" + sectref.replace('%', '_');
                } else {
                    matchedLink = reallink;
                }
                url = makeBasicURL(m_context, matchedLink, parms, m_absolute) + sectref;
            } else {
                String reallink = MarkupParser.cleanLink(m_ref);
                url = makeBasicURL(m_context, reallink, parms, m_absolute);
            }
        }
    } else if (m_pageName != null && m_pageName.length() > 0) {
        WikiPage p = engine.getPage(m_pageName);
        String parms = (m_version != null) ? "version=" + getVersion() : null;
        parms = addParamsForRecipient(parms, m_containedParams);
        if (p instanceof Attachment) {
            String ctx = m_context;
            // attachment, but don't override the context setting otherwise
            if (m_context == null || m_context.equals(WikiContext.VIEW)) {
                ctx = WikiContext.ATTACH;
            }
            url = engine.getURL(ctx, m_pageName, parms, m_absolute);
        // url = m_wikiContext.getURL( ctx, m_pageName, parms );
        } else {
            url = makeBasicURL(m_context, m_pageName, parms, m_absolute);
        }
    } else {
        String page = engine.getFrontPage();
        url = makeBasicURL(m_context, page, null, m_absolute);
    }
    return url;
}
Also used : LinkParsingOperations(org.apache.wiki.parser.LinkParsingOperations) WikiPage(org.apache.wiki.WikiPage) Attachment(org.apache.wiki.attachment.Attachment) WikiEngine(org.apache.wiki.WikiEngine)

Example 60 with Attachment

use of org.apache.wiki.attachment.Attachment in project jspwiki by apache.

the class LinkToParentTag method doWikiStartTag.

public int doWikiStartTag() throws IOException {
    WikiPage p = m_wikiContext.getPage();
    // 
    if (p instanceof Attachment) {
        setPage(((Attachment) p).getParentName());
    } else {
        String name = p.getName();
        int entrystart = name.indexOf("_blogentry_");
        if (entrystart != -1) {
            setPage(name.substring(0, entrystart));
        }
        int commentstart = name.indexOf("_comments_");
        if (commentstart != -1) {
            setPage(name.substring(0, commentstart));
        }
    }
    return super.doWikiStartTag();
}
Also used : WikiPage(org.apache.wiki.WikiPage) Attachment(org.apache.wiki.attachment.Attachment)

Aggregations

Attachment (org.apache.wiki.attachment.Attachment)62 WikiPage (org.apache.wiki.WikiPage)26 Test (org.junit.Test)23 File (java.io.File)20 ProviderException (org.apache.wiki.api.exceptions.ProviderException)17 Collection (java.util.Collection)13 Date (java.util.Date)11 Iterator (java.util.Iterator)10 WikiEngine (org.apache.wiki.WikiEngine)10 AttachmentManager (org.apache.wiki.attachment.AttachmentManager)7 FileInputStream (java.io.FileInputStream)6 IOException (java.io.IOException)6 List (java.util.List)6 Vector (java.util.Vector)6 WikiContext (org.apache.wiki.WikiContext)5 Hashtable (java.util.Hashtable)4 Element (net.sf.ehcache.Element)4 PagePermission (org.apache.wiki.auth.permissions.PagePermission)4 ArrayList (java.util.ArrayList)3 Calendar (java.util.Calendar)3