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();
}
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 "";
}
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;
}
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;
}
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);
}
}
Aggregations